Reassigning Smart Pointers

Generally speaking, smart pointers, such as std::unique_ptr and Glib::RefPtr , delete their object when reassigned to point to another object, given that they are the only pointers holding this object (obviously implied in the case of std::unique_ptr )?

+7
c ++ c ++ 11 smart-pointers glib gtkmm
source share
2 answers

For unique_ptr::reset , [unique.ptr.single.modifiers] / 4:

Effects: assigns the saved pointer p , and then , if the old value of the saved pointer old_p not nullptr , calls get_deleter()(old_p) .

Or the move destination operator=(unique_ptr&& u) , operator=(unique_ptr&& u) in [unique.ptr.single.asgn] / 2:

Transfer ownership from u to *this as if by calling reset(u.release()) followed by get_deleter() = std::forward<D>(u.get_deleter()) .

(Equivalent to another assignment statement template)


For shared_ptr reassignment is slightly different. shared_ptr will never destroy the reference object unless it is the last remaining one that owns it, so let's assume this is given.
shared_ptr::reset(Y*) points to [util.smartptr.shared.mod] / 3:

Effects: equivalent to shared_ptr(p).swap(*this) .

But, obviously, the temporary is destroyed at the end of the function call, destroying the hold object (if applicable).
The same behavior operator=(shared_ptr<> const&) has, [util.smartptr.shared.assign] / 1 and 4:

Effects: equivalent to shared_ptr(r).swap(*this) .

... move assignment operator (pattern), r is shared_ptr<>&& :

Effects: equivalent to shared_ptr(std::move(r)).swap(*this) .

If *this was the last owner of the object, now it is temporary - which will be destroyed inside.


For Glib::RefPtr script is similar to shared_ptr : the copy assignment operator (and the template of the assignment operator) are defined with the same semantics. If something else is assigned to the current RefPtr value, the current object reference counter decreases and is destroyed if the total counter value is zero.

+9
source share

For unique_ptr, the answer is yes:

An object is destroyed, and its memory is freed when any of the following s occurs :

  • unique_ptr object management is destroyed
  • unique_ptr, which controls the object, is assigned another pointer using the = or reset () operator.

The object is destroyed using a potentially remote user calling Deleter (ptr). The delector calls the object's destructor and allocates memory.

+3
source share

All Articles