quot;Rightquot; way to deallocate an std::vector object(“对释放 std::vector 对象的方法)
问题描述
第一个解决方案是:
std::vector<int> *vec = new std::vector<int>;
assert(vec != NULL);
// ...
delete vec;
替代方案是:
std::vector<int> v;
//...
vec.clear();
vec.swap(std::vector<int>(vec));
第二个解决方案有点诡计——什么是正确的"?怎么做?
The second solution's a bit of a trick --- what's the "right" way to do it?
我知道析构函数一旦离开堆栈就会被调用,我对其他方法很好奇.
I'm aware that the destructor will be called once it's off the stack, I was curious about other methods.
推荐答案
释放向量的最简单、最可靠的方法是在堆栈上声明它,然后什么都不做.
The simplest and most reliable way to deallocate a vector is to declare it on the stack and simply do nothing.
void Foo() {
std::vector<int> v;
...
}
C++ 保证在方法执行时会调用v 的析构函数.std::vector 的析构函数将确保它分配的任何内存都被释放.只要 vector 的 T 类型具有适当的 C++ 释放语义,一切都会好起来的.
C++ guarantees that the destructor of v will be called when the method executes. The destructor of std::vector will ensure any memory it allocated is freed. As long as the T type of the vector<T> has proper C++ deallocation semantics all will be well.
这篇关于“对"释放 std::vector 对象的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:“对"释放 std::vector 对象的方法
基础教程推荐
- C++:获取传递给函数的多维数组的行大小 2021-01-01
- 如何在 C++ 中正确使用命名空间? 2022-01-01
- 将不可复制的闭包对象传递给 std::function 参数 2021-01-01
- 随机插入/删除的综合向量与链表基准 2022-01-01
- 提升 ASIO 流缓冲 2021-01-01
- c++ STL设置差异 2022-01-01
- 为什么我们不能使用“虚拟继承"?在 COM 中? 2022-01-01
- 如何更改 SysDateTimePick32 或 CDateTimeCtrl 的背景颜色? 2022-01-01
- 如何部分禁用 cmake C/C++ 自定义编译器检查 2021-01-01
- 与 CAS 的原子交换(使用 gcc 同步内置函数) 2022-01-01
