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!
The problem here is that somewhere, your code is attempting to call the "copy-assignment" operator of
Foo
.This causes the compiler to attempt to generate a copy-assignment operator which calls the copy-assignment operators of all the subobjects of
Foo
. Eventually, this leads to an attempt to copy aunique_ptr
, an operation which is not possible.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 usingstd::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.
An excerpts from www.cplusplus.com
unique_ptr assignment The object acquires the ownership of x's content, including both the stored pointer and the stored deleter (along with the responsibility of deleting the object at some point). Any object owned by the unique_ptr object before the call is deleted (as if unique_ptr's destructor was called).
But there is a warning too:
This page describes a feature introduced by the latest revision of the C++ standard (2011). Older compilers may not support it.
MSVC 2010 defines
operator=
as private (non-copyable) but supportsswap
method.You can't use unique_ptr in vector because vector implementation strongly relies on values assign operator, which is private in
unique_ptr
. Useshared_ptr
from boost or other smart ptr implementation from C++11.Often a
std::move(iUniquePtr)
is missing somewhere (e. g. when using push_back).