是否在清除后释放 std::vector 内存?

2021-12-20 00:00:00 optimization memory vector c++

假设我有一个 std::vector 结构体.如果向量被 clear() 处理,内存会发生什么变化?

Suppose I have a std::vector of structs. What happens to the memory if the vector is clear()'d?

std::vector<myStruct> vecs;
vecs.resize(10000);
vecs.clear();

内存会被释放,还是作为可重用的缓冲区附加到 vecs 变量上?

Will the memory be freed, or still attached to the vecs variable as a reusable buffer?

推荐答案

内存仍然附着在向量上.这也不仅仅是可能的.这是必需的.特别是,如果您要在调用 clear() 后再次向向量添加元素,则在您添加的元素数量超过之前设置的 1000 个元素之前,向量不得重新分配.

The memory remains attached to the vector. That isn't just likely either. It's required. In particular, if you were to add elements to the vector again after calling clear(), the vector must not reallocate until you add more elements than the 1000 is it was previously sized to.

如果你想释放内存,通常是用一个空向量交换.C++11 还添加了一个 shr??ink_to_fit 旨在更直接地提供大致相同功能的成员函数,但它是非绑定的(换句话说,它可能会释放额外的内存,但仍然不是真正需要这样做).

If you want to free the memory, the usual is to swap with an empty vector. C++11 also adds a shrink_to_fit member function that's intended to provide roughly the same capability more directly, but it's non-binding (in other words, it's likely to release extra memory, but still not truly required to do so).

相关文章