c++ - 是否需要 "nested"释放 std::vector<pair<vector<int>,int>> 中的保留内存以手动释放它?

标签 c++ c++11 memory-management

我有:

vector< pair<vector<int> , int> > mapped_samples;

这是非常大的。我会手动释放内存。我知道简单 vector 的技巧是:

vector<int> simple_vector;
vector<int>().swap(simple_vector); 

在我的情况下,可以这样做:

vector<pair<vector<int> , int>>().swap(mapped_samples);

还是有必要做一些嵌套操作?

(我正在使用 C++11)

最佳答案

如果您绝对必须保证在函数作用域退出之前清理 vector,只需添加额外的作用域。

原始代码:

... myfunc(...) {

    ... stuff without vector ...

    vector< pair<vector<int> , int> > mapped_samples;

    ... stuff using vector ...

    ... more stuff without vector ...

}

为了确保 vector 在东西停止使用后完全消失,只需添加大括号:

... myfunc(...) {

    ... stuff without vector ...

    {  // Start of vector's block scope
        vector< pair<vector<int> , int> > mapped_samples;

        ... stuff using vector ...

    }  // End of vector's block scope, guaranteed to be cleaned here

    ... more stuff without vector ...

}

这比 swap 技巧(必须创建和销毁垃圾 vector)更干净,而且更通用;它适用于所有 RAII 资源,实际上是使用 std::lock_guard 的常用方法.

关于c++ - 是否需要 "nested"释放 std::vector<pair<vector<int>,int>> 中的保留内存以手动释放它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44158835/

相关文章:

javascript - 从 C++ 回调函数发出 Node.js 事件

c++ - 为什么 `std::exit` 没有按预期触发析构函数?

c - 分配内存并将输入从文件读取到结构数组

大数据集的 Python 内存错误

c++ - vector 元组并向后推

NSOperation 和 NSOperationQueue 的 C++ 等价物

c++ - 如何自定义 C++ 列表容器,使其可以容纳不同类型的结构?

c++ - 位摆弄黑客 : most efficient way to remove one bit every n bits?

c++ - 如果我在 C++ 中使用 operator new[] 分配一个对象数组,但单独解除分配它们是否仍然构成内存泄漏?

c++在std::vector中存储逗号分隔的int的最快方法是什么