新似乎没有办法增加或减少分配?

new doesn't seem to have a way to grow or shrink allocations?

本文关键字:分配 增加 新似乎      更新时间:2023-10-16

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

在模拟期间,CCD_ 3可以变化。如果npoints增加,我想增加分配的内存。此外,如果npoints减少,我想删除减少的内存。

使用::std::vector

#include <vector>
void foo()
{
::std::vector<double> x;
x.resize(5);
x[4] = 2.0;
x.resize(2);
// etc...
}

您提到的用例正是::std::vector产生的原因。

现在,如果将向量的大小调整得更小,它通常不会释放内存。这有很多原因,shrink_to_fit上的StackOverflow问题描述了为什么: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...
}

矢量仍然可能不会实际缩小分配。如果这真的是一个问题,那么这是一个需要在实现中解决的问题。

如果的问题,并且您必须缩减分配,并且无法修复实现,那么您可以这样做:

#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);
}
}

然后打电话给

shrinkwrap_vector(x);

而不是x.shrink_to_fit()。这只需要将您的向量复制到一个全新的向量中,该向量的大小与您的实现所允许的大小一样接近。

还要注意,如果您存储的东西有一个非平凡的析构函数(double有一个平凡的析构函数),那么在执行resize时,将为每个丢弃的元素调用该析构函数。整个shrink_to_fit只是关于内存分配,而不是关于构建或销毁。

最后,如果您真的、真的想使用mallocrealloc调用,那么您可以创建一个使用这些调用的自定义vector类。不过,除非您将自定义类指定为double,否则您必须格外小心。您必须对分配内存后添加的任何元素调用构造函数,并在释放内存之前对任何丢弃的元素调用析构函数。

写这类课很复杂。您需要符合对C++中容器类的期望,以使它能够顺利地与其他一切一起工作。这包括生成迭代器类和类似性质的东西。