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

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

问题描述

限时送ChatGPT账号..

假设我有一个 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 内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

OpenGL transforming objects with multiple rotations of Different axis(OpenGL 变换不同轴多次旋转的对象)
GLFW first responder error(GLFW 第一响应者错误)
SOIL not linking correctly(SOIL 连接不正确)
Core profile vs version string? Only getting GLSL 1.3/OGL 3.0 in mesa 10.0.1(核心配置文件与版本字符串?在 mesa 10.0.1 中只获得 GLSL 1.3/OGL 3.0)
What is the range of OpenGL texture ID?(OpenGL 纹理 ID 的范围是多少?)
How taxing are OpenGL glDrawElements() calls compared to basic logic code?(与基本逻辑代码相比,OpenGL glDrawElements() 调用的繁重程度如何?)