[英]std::allocator deallocate part of memory
I am reading about c++ allocators and the deallocate function has sentence that got my attention:我正在阅读有关 C++ 分配器的信息,并且解除分配函数的句子引起了我的注意:
The argument n must be equal to the first argument of the call to allocate() that originally produced p;参数n 必须等于最初产生p 的allocate() 调用的第一个参数; otherwise, the behavior is undefined.否则,行为未定义。
Why is that?这是为什么? Why couldn't one deallocate part of the allocated memory, stupid example:为什么不能释放分配的内存的一部分,愚蠢的例子:
#include <memory>
#include <string>
int main()
{
std::allocator<std::string> alloc;
auto const p = alloc.allocate(20);
alloc.deallocate(p+10, 10);
return 0;
}
Some allocators might be able to do that.一些分配器可能能够做到这一点。 The C++ specification only says what all implementations of the abstract allocator interface, Alloc<T>
, are required to do. C++ 规范只说明了抽象分配器接口Alloc<T>
所有实现都需要做什么。 The committee decided not to require the feature you are asking about.委员会决定不需要您所询问的功能。
I don't have the C++ Rationale on this computer, but I suspect that the feature you are asking about is not required because the C memory allocator functions ( malloc
and free
) cannot do it, 1 and the C++ committee wanted it to be possible to implement the C++ library on top of the C library.我在这台计算机上没有 C++ 基本原理,但我怀疑您所询问的功能不是必需的,因为 C 内存分配器函数( malloc
和free
)无法做到这一点, 1和 C++ 委员会希望它成为可能在 C 库之上实现 C++ 库。
1 yes, realloc
can do some cases of this, but not all of them 1是的, realloc
可以做一些这样的事情,但不是全部
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.