Is std::vector memory freed upon a clear?(是否在清除后释放 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 还添加了一个 shrink_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 内存?
基础教程推荐
- 使用从字符串中提取的参数调用函数 2022-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01