在C中,标准内存处理函数是malloc(),realloc()和free().但是,C++ stdlib分配器只兼容其中两个:没有重新分配功能.当然,不可能完全相同realloc(),因为简单地复制内存不适合非聚合类型.但是,这个函数是否会出现问题:
bool reallocate (pointer ptr, size_type num_now, size_type num_requested);
Run Code Online (Sandbox Code Playgroud)
哪里
ptr先前为num_now对象分配了相同的分配器;num_requested> = num_now;和语义如下:
ptr从给定num_now对象的大小扩展给定的内存块num_requested,它会这样做(留下额外的内存未初始化)并返回true;false.当然,这不是很简单,但据我所知,分配器主要用于容器和容器的代码通常很复杂.
给定这样的函数,std::vector比如说,可以增长如下(伪代码):
if (allocator.reallocate (buffer, capacity, new_capacity))
capacity = new_capacity; // That's all we need to do
else
... // Do the standard reallocation by using a different buffer,
// copying data and freeing the current one …Run Code Online (Sandbox Code Playgroud)