【发布时间】:2020-12-20 11:02:41
【问题描述】:
我有一个std::vector<std::unique_ptr<Kind>>,我想在对其进行迭代时对其进行清理,而无需显式调用其成员的析构函数 (.reset())。
Kind 是一个沉重的结构,它的大小在迭代过程中会增加。下一个对象不需要知道以前的对象,所以我想在不需要时清理一个迭代。
我知道 vector 最终会清理干净,但是到那时,大量的 Kind 和它们动态分配的内存加起来。我正在尝试将峰值内存减少到一个元素。
我想避免reset,因为其他开发人员可能不知道动态分配,忘记在循环结束时调用 reset 并消耗内存。
我无法创建副本,
for(std::unique_ptr<Kind> t : store)
我不能像这样移动它
for(std::unique_ptr<Kind> &&t : store)
那我该怎么做呢?
#include <iostream>
#include <vector>
struct Kind{
char a;
char *array;
Kind(const char c): a(c)
{
}
~Kind(){
free(array); // internal custom deallocator.
}
};
int main() {
std::vector<std::unique_ptr<Kind>> store;
store.push_back(std::make_unique<Kind>('y'));
store.push_back(std::make_unique<Kind>('z'));
for(std::unique_ptr<Kind> &t : store){
// increase size of Kind.array.
std::cout << t->a;
// Use the Kind.array
// clean up t automatically.
}
return 0;
}
【问题讨论】:
标签: c++ for-loop unique-ptr raii ownership