如何使用唯一的指针向量? [英] How to use unique pointer vector?
问题描述
我使用 vector
来存储我的数据,以实现其自动内存管理和 unique_ptr
的低成本.我有一个函数可以尝试向其中添加新创建的数据.数据可能真的添加或不添加.它是添加的,我不需要关心它的内存删除,因为指针向量会处理它.如果没有添加,希望新创建的数据可以自动删除.有什么简单的实现方法吗?该函数可能如下所示或其他类似的形式.谢谢.
I use vector<unique_ptr<Data>>
to store my data for its automatic memory management and low cost of unique_ptr
. I have a function to try to add new created data into it. The data may be really added or not. It it is added, I don't need to care about its memory deletion because the pointer vector will take care of it. If it is not added, I hope the new created data can be deleted automatically. Any simple way to implement it? The function may look like below or other similar forms. Thanks.
// Return true if really added, return flase if not.
bool add(vector<unique_ptr<Data>>& vec, Data* newData);
根据戴夫的回答,bool add(vector
比 unique_ptr
更好代码>非公开可复制?这里在第二个参数中使用了一个引用.
Based on Dave's answer, is bool add(vector<unique_ptr<Data>>& vec, std::unique_ptr<Data>& newData)
better since unique_ptr
non public copyable? Here a reference is used in the 2nd argument.
推荐答案
将 newData
也接受为 unique_ptr
.
bool add(vector<unique_ptr<Data>>& vec, std::unique_ptr<Data> newData)
{
if(blah blah blah)
{
vec.push_back(std::move(newData));
return true;
}
return false;
}
这篇关于如何使用唯一的指针向量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!