I'd like to have a vector of unique_ptr's as a member of a class I'm making.
class Foo {
[...]
private:
vector<unique_ptr<Bar>> barList;
}
But then I start getting cryptic error messages from the VS2010 compiler:
error C2248: 'std::unique_ptr<_Ty>::operator =' : cannot access private member declared in class 'std::unique_ptr<_Ty>'
Along with a handful of error lines below that which dive into Microsoft's implementation of std::_Copy_impl<>
...
I changed the member declaration to
vector<unique_ptr<Bar>>* barList;
And it compiles. But I can't help but wonder why I can't do it the way I originally wanted? For grins, I tried this and it works fine:
vector<Bar> barList;
But now I lose the convenience of unique_ptr
. I want my cake and I want to eat it too!
A unique_ptr can only be moved. This means that the ownership of the memory resource is transferred to another unique_ptr and the original unique_ptr no longer owns it. We recommend that you restrict an object to one owner, because multiple ownership adds complexity to the program logic.
(since C++11) std::unique_ptr is a smart pointer that owns and manages another object through a pointer and disposes of that object when the unique_ptr goes out of scope.
An unique_ptr has exclusive ownership of the object it points to and will destroy the object when the pointer goes out of scope. A unique_ptr explicitly prevents copying of its contained pointer.
std::unique_ptr represents data which has only one owner at any given time. It should be your default choice when you need a smart pointer. You can move a std::unique_ptr around to keep it alive, but there can only be one owner of the data. After moving the pointer, the previous pointer object is invalidated.
Often a std::move(iUniquePtr)
is missing somewhere (e. g. when using push_back).
unique_ptr
doesn't have copy semantics, so you can't use any methods that would copy the contained object. You can do this with rvalue references by using std::move
in the place(s) it's trying to make a copy. Without seeing your code I can't say where that would be.
If it compiles in the second form either you didn't exercise the same code or there's a compiler bug. Both should fail the same way.
Your third example, storing by value is the simplest way unless your objects are large and expensive to store/copy around by value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With