No code to show but a general question
If you have a class that has a unique ptr in it, how is the difference between shallow copy and deep copy relevant?
Shallow copy will leave you with double-free and dangling pointer errors, generally UB.
You can't have shallow copy with std::unique_ptr<T>
members since the whole point of std::unique_ptr<T>
is single ownership. On the other hand a type with members of typestd::shared_ptr<T>
will work as expected, since shared_ptr
is reference counted.
To expand upon the above difference from another direction, in an attempt to better explain the comment, the unique ownership premise of unique_ptr
requires both unique_ptr(const unique_ptr<T>&)
and unique_ptr& operator=(const unique_ptr<T>&)
be = delete;
since either would violate the guarantee. Moreover, you'll need to provide some extension method which allowed cloning the pointed to object. shared_ptr
conceptually involves incrementing a reference count in either case and there's no cloning required.
You could, in theory, allocate objects from some other reusable pool and provide a custom deleter to your unique_ptr
which does nothing. But why bother? Simply use shared_ptr
if you want shared ownership.
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