Reputation: 3164
On C++ primer 5 edition. Chapter 12. Dynamic memory: It is written:
shared_ptr p(u); P assumes ownership from the
uniqe_ptr
u
; makesu
null. shared_ptr p(q, d) Assumes ownership for the object to which the built-in pointerq
points.q
must be convertible toT*
($4.11.2, p.161).p
will use the callable objectd
($10.3.2, p.388) in place ofdelete
to freeq
.
unque_ptr
and for the object to which the built-in...".Can someone explain to me this paragraph? Thanks so much.
Upvotes: 1
Views: 111
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
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_ptr
s, 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