C++ 是否在清除时释放 std::vector 内存?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13944886/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 17:50:47  来源:igfitidea点击:

Is std::vector memory freed upon a clear?

c++memoryvector

提问by Jerry Coffin

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

假设我有一个 std::vector 结构体。如果向量被 clear()'d,内存会发生什么?

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

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

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

回答by Jerry Coffin

The memory remains attached to the vector. If you want to free it, the usual is to swap with an empty vector. C++11 also adds a shrink_to_fitmember 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).

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

回答by Alexander Chertov

The vector's memory is not guaranteed to be cleared. You cannot safely access the elements after a clear. To make sure the memory is deallocated Scott Meyers advised to do this:

不保证会清除向量的内存。清除后您无法安全地访问元素。为了确保内存被释放,Scott Meyers 建议这样做:

vector<myStruct>().swap( vecs );

Cplusplus.comhas the following to say on this:

Cplusplus.com对此有以下说法:

Removes all elements from the vector, calling their respective destructors, leaving the container with a size of 0.

The vector capacity does not change, and no reallocations happen due to calling this function. A typical alternative that forces a reallocation is to use swap:...

从向量中移除所有元素,调用它们各自的析构函数,使容器的大小为 0。

向量容量不会改变,也不会因为调用这个函数而发生重新分配。强制重新分配的典型替代方法是使用交换:...

回答by Ryan Guthrie

The destructor is called on the objects, but the memory remains allocated.

对对象调用析构函数,但内存保持分配。

回答by BAK

No, memory are not freed.

不,内存没有被释放。

In C++11, you can use the shrink_to_fitmethod for force the vector to free memory.

在 C++11 中,您可以使用shrink_to_fit强制向量释放内存的方法。

http://www.cplusplus.com/reference/vector/vector/

http://www.cplusplus.com/reference/vector/vector/