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

Is std::vector memory freed upon a clear?(是否在清除后释放 std::vector 内存?)

本文介绍了是否在清除后释放 std::vector 内存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个 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).

这篇关于是否在清除后释放 std::vector 内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:是否在清除后释放 std::vector 内存?

基础教程推荐