相关疑难解决方法(0)

为什么C++分配器中没有重新分配功能?

在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)

c++ memory-management realloc

33
推荐指数
3
解决办法
3829
查看次数

标签 统计

c++ ×1

memory-management ×1

realloc ×1