我有:
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/