Itachi Uchiwa
Itachi Uchiwa

Reputation: 3164

C++ primer 5 edition: shared_ptr initialized from uniqe_ptr?

On C++ primer 5 edition. Chapter 12. Dynamic memory: It is written:

shared_ptr p(u); P assumes ownership from the uniqe_ptr u; makes u null. shared_ptr p(q, d) Assumes ownership for the object to which the built-in pointer q points. q must be convertible to T* ($4.11.2, p.161). p will use the callable object d ($10.3.2, p.388) in place of delete to free q.

Can someone explain to me this paragraph? Thanks so much.

Upvotes: 1

Views: 111

Answers (2)

Oblivion
Oblivion

Reputation: 7374

The book is not clear with types. you need an rvalue ref to construct a shared_ptr from unique_ptr:

template< class Y, class Deleter >
shared_ptr( std::unique_ptr<Y,Deleter>&& r );

check this code:

unique_ptr<int> up{new int{10}};
shared_ptr<int> sp(move(up));
cout << *sp <<'\n';
//cout << *up <<'\n'; // up is nullptr

Live ob Godbolt


smart pointers manage the lifetime of raw pointer they own. unique_ptr doesn't share ownership while shared_ptr does. When you construct a shared_ptr from a unique_ptr you have to give up its ownership via move, and unique_ptr cannot be copied.

I think by using "assumes ownership" the author wants to state that, bad things can still happen if you somehow modify the pointer owned by smart pointers.

Upvotes: 5

catnip
catnip

Reputation: 25388

Smart pointers 'own' (or, perhaps better, 'manage') an underlying raw pointer or object.

unique_ptr owns the pointer outright and will delete it when it goes out of scope. shared_ptr potentially shares ownership with other shared_ptrs, and the managed object will be deleted when the last shared_ptr goes out of scope.

So, in your example, the newly created shared_ptr takes over ownership from the unique_ptr, leaving the latter owning nothing.

Upvotes: 2

Related Questions