“右”方法来释放std :: vector对象 [英] "Right" way to deallocate an std::vector object

查看:180
本文介绍了“右”方法来释放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 的析构函数将确保它分配的任何内存被释放。只要向量< T> 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对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆