c++ - Can I use a `unique_ptr` in a vector, or do I need to switch to `shared_ptr`? -
given class unique_ptr:
class myclass { public: myclass(){} myclass(myclass &&other) : ptr(std::move(other.ptr)){} std::unique_ptr <int> ptr; };
is there way make possible have std::vector<myclass>
?
void thisbreaksit() { myclass instance; std::vector<myclass> mv; mv.push_back(instance); }
as-is, gives me error
error c2248: 'std::unique_ptr<_ty>::unique_ptr' : cannot access private member declared in class 'std::unique_ptr<_ty>'
this makes sense, since have no copy constrctor, , when compiler tries creating default copy constructor, tries copying unique_ptr
, isn't allowed.
i can make compile adding constructor:
myclass(const myclass&){}
but of course, leaves unique_ptr
uninitialized, , not want.
i can't add
myclass(const myclass& other) : ptr(std::move(other.ptr)){}
because it's const
, , cant call std::move() on const
object. can create constructor
myclass(myclass& other) : ptr(std::move(other.ptr)){}
but doesn't solve original compile error, vector::push_back
uses const
copy constructor.
so, i'm stuck. there way i'm trying do?
all of these issues go away if use shared_ptr
instead of unique_ptr
. should doing?
there's no problem storing non-copyable type in vector; it's required movable, yours is.
the problem this:
mv.push_back(instance);
tries insert copy of instance
, , class not copyable. movable:
mv.push_back(std::move(instance));
note there's no need write own default , move constructors in example. implicit ones yours do.
Comments
Post a Comment