Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deep and shallow cloning with unique pointers

Tags:

c++

unique-ptr

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?

like image 663
davidlingg2000 Avatar asked Dec 31 '22 20:12

davidlingg2000


1 Answers

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.

like image 116
Tanveer Badar Avatar answered Jan 12 '23 17:01

Tanveer Badar