Reputation: 13575
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);
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.
Upvotes: 2
Views: 4549
Reputation: 154047
What are the semantics you want to achieve.
FWIW: a vector of unique_ptr is rarely a good idea. If you want the vector to have exclusive ownership, you're better off using Boost's pointer vector.
Upvotes: -1
Reputation: 28178
Accept newData
as a unique_ptr
too.
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;
}
Upvotes: 8