davidlingg2000
davidlingg2000

Reputation: 117

Deep and shallow cloning with unique pointers

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?

Upvotes: 7

Views: 1038

Answers (2)

Tanveer Badar
Tanveer Badar

Reputation: 5522

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.

Upvotes: 7

siniarskimar
siniarskimar

Reputation: 66

Shallow copying pointers with default copy constructor will leave you with dangling pointers. (pointer to unallocated/freed memory)

unique_ptr is non-copyable. The pointer can be only moved into another unique_ptr or made into shared_ptr. The whole purpose of unique_ptr is to have one reference (in this case a pointer) to some block of memory

This means that shallow copy with unique_ptr is impossible.

Upvotes: 2

Related Questions