new似乎没有办法增长或缩减分配?

0 c++ pointers memory-management allocation c++11

我在x轴上有n个点.在程序开始时,我正在分配x npoints.例如x = new double[npoints];

在模拟期间npoints可能会有所不同 如果npoints增加我想增加分配的内存.此外,如果npoints减少我想删除减少的内存.

Omn*_*ous 10

用一个::std::vector.

#include <vector>

void foo()
{
    ::std::vector<double> x;
    x.resize(5);
    x[4] = 2.0;
    x.resize(2);
    // etc...
}
Run Code Online (Sandbox Code Playgroud)

您提到的用例正是为什么::std::vector要这样做的.

现在,如果您将矢量调整为较小,则通常不会释放内存.这有很多原因,这个StackOverflow问题shrink_to_fit描述了原因:shrink_to_fit是否正确地将`std :: vector`的容量减小到了它的大小?

但是,如果您真的想暗示应该释放额外点的实现,请执行以下操作:

#include <vector>

void foo()
{
    ::std::vector<double> x;
    x.resize(5);
    x.shrink_to_fit(); // It didn't get smaller here, but I'm guessing you may
    x[4] = 2.0;        // not know that when you resize the vector in your own code.
    x.resize(2);
    x.shrink_to_fit();
    // etc...
}
Run Code Online (Sandbox Code Playgroud)

向量仍然可能实际上不会缩小分配.如果它确实是一个问题,那么这是一个需要考虑实施的问题.

如果它一个问题,你绝对必须缩小分配并且无法修复实现,那么你可以这样做:

#include <iterator>
#include <algorithm>
#include <utility>
#include <vector>

template <class T>
void shrinkwrap_vector(::std::vector<T> &x)
{
   using namespace ::std;
   typedef vector<T> vec_t;

   const auto old_cap = x.capacity();
   x.shrink_to_fit(); // Try shrink_to_fit first to see if it works.
   if ((x.capacity() == old_cap) && (old_cap > x.size())) {
      vec_t t;
      t.reserve(x.size());
      move(x.begin(), x.end(), back_inserter(t));
      swap(x, t);
   }
}
Run Code Online (Sandbox Code Playgroud)

然后打电话

shrinkwrap_vector(x);
Run Code Online (Sandbox Code Playgroud)

在你的代码而不是x.shrink_to_fit().这只会将您的矢量复制到一个全新的矢量中,该矢量的大小与您的实现可以获得的大小相近.

还要注意,如果你存储的东西有一个非平凡的析构函数(double有一个简单的析构函数),那么当你这样做时,每个被删除的元素都会调用析构函数resize.整个shrink_to_fit事情完全是关于内存分配,而不是关于构建或破坏.

最后,如果你真的想要使用C mallocrealloc调用,你可能能够创建一个vector使用它们的自定义类.除非您使自定义类具体,否则您必须格外小心double.您必须在分配内存后添加的任何元素上调用构造函数,并在释放内存之前调用任何已删除元素上的析构函数.

写这种类很复杂.您需要符合C++中容器类的期望,以使其与其他所有内容一起顺利运行.这包括制作迭代器类和那种性质的东西.

  • 调整为较低的值不会释放内存.如果释放内存至关重要,则可能必须使用vector :: shrink_to_fit()函数. (3认同)
  • @Omnifarious否则,减小向量的大小将使所有迭代器和所有指针以及对向量成员的引用无效. (3认同)