简体   繁体   English

C ++:在没有cstdlib的情况下重新分配内存

[英]C++: Reallocating memory without cstdlib

Couldn't find exact answer to the question: 无法找到问题的确切答案:

Is freeing memory and allocating again the only way to reallocate memory without using cstdlib? 是否释放内存并再次分配重新分配内存而不使用cstdlib的唯一方法? If not so, then what are the possible solutions? 如果不是这样,那么可能的解决方案是什么?

Thanks in advance. 提前致谢。

Perhaps you mean like what is done with a std::vector (or other container) when you load it with memory, remove all the elements, then call clear to free the memory, then allocating new items within it, thus allocating more memory? 也许你的意思就像用内存加载std :: vector(或其他容器)时所做的那样,删除所有元素,然后调用clear释放内存,然后在其中分配新项,从而分配更多内存? In this case, as the memory in the container grows, the container may realloc its memory as needed. 在这种情况下,随着容器中的内存增长,容器可以根据需要重新分配其内存。

Since you mention you are creating a Vector: 既然你提到你正在创建一个Vector:

In projects where we needed to do this because we did not have a vector implementation (embedded), it is common to allocate a set chunk of memory larger than what is intiially required to prevent constant memory reallocations, which incur large copy costs and cause memory fragmentation. 在我们需要执行此操作的项目中,因为我们没有矢量实现(嵌入式),所以通常会分配一个大于内存所需的内存块,以防止常量内存重新分配,从而导致大量复制成本并导致内存碎片。 A common scheme was to allocate a "reasonable" size for the app, then double that size if the limit is reached. 一个常见的方案是为app分配一个“合理”的大小,然后在达到限制时加倍。 If the user ever requested the buffer be reduced in size, or set to a size at initialization, then we ignore this heuristic and use the requested size. 如果用户曾要求缓冲区大小减小,或者在初始化时设置为大小,那么我们将忽略此启发式并使用所请求的大小。

If you are implementing your own vector class, then you do need to properly copy the contents of the vector, not use realloc , since you don't know what the object itself is doing when it is being copied (or in C++11 for relevant cases, moved). 如果你正在实现自己的向量类,那么你需要正确地复制向量的内容,而不是使用realloc ,因为你不知道对象本身在被复制时做了什么(或者在C ++ 11中)对于相关案件,已移动)。 Imagine for example that you have an object that does something like this: 想象一下,例如你有一个像这样的对象:

class B;

class A
{
  private:
    B* bp;
  public:
    A(B *p) : bp(p)
    {
    }
};


class B
{
  public:
   A a;
   B() : A(this)
   {
      ... 
   }
 };

MyVector<B> v; 

If you copy the object to a different address, without calling the constructor, the bp pointer in A will point to some "random" place. 如果将对象复制到另一个地址而不调用构造函数,则Abp指针将指向某个“随机”位置。 That would be a pretty nasty bug to try to find. 试图找到这将是一个非常讨厌的错误。

[And yes, there is a bunch of stuff missing in the above classes - it is not meant as a complete class declaration, etc, etc] [是的,上面的类中缺少一些东西 - 它不是一个完整的类声明等等]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM