Generally speaking do smart pointers such as std::unique_ptr and Glib::RefPtr delete their object when reassigned to point at another object, given they are the only pointers holding that given object (obviously implied in case of std::unique_ptr)?
- 303
- 1
- 2
- 9
2 Answers
For unique_ptr::reset, [unique.ptr.single.modifiers]/4:
Effects: assigns
pto the stored pointer, and then if the old value of the stored pointer,old_p, was not equal tonullptr, callsget_deleter()(old_p).
Or the move assignment operator, operator=(unique_ptr&& u) in [unique.ptr.single.asgn]/2:
Transfers ownership from
uto*thisas if by callingreset(u.release())followed byget_deleter() = std::forward<D>(u.get_deleter()).
(Equivalent for the other assignment operator template)
For
shared_ptr, reassignment is a little bit different. shared_ptr will never destroy a referenced object when it's not the last remaining one owning it, so let's assume that is given.shared_ptr::reset(Y*) specifies in [util.smartptr.shared.mod]/3:
Effects: Equivalent to
shared_ptr(p).swap(*this).
But clearly the temporary gets destroyed at the end of the function call, destroying the hold object (if applicable).
That is 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 (template), r is shared_ptr<>&&:
Effects: Equivalent to
shared_ptr(std::move(r)).swap(*this).
If *this was the last owning the object, then now the temporary is - which will be destroyed inside.
For Glib::RefPtr the scenario is similar to shared_ptr: The copy assignment operator (and an assignment operator template) are defined with the same semantics. If the current RefPtr is assigned to something else, the currently hold objects reference counter is decremented and its destroyed if the resulting counter value is zero.
- 60,038
- 8
- 155
- 203
-
RefPtr
something = getSomething(); something = getSomethingElse(); works fine. You shouldn't need to use RefPtr::swap(). Of course the reassignment here just decreases the reference on the first Something rather than deleting it. It's a reference-counting _shared_ smartpointer. – murrayc Dec 07 '14 at 19:18 -
@murrayc I must have misread the documentation the first time I went over it. Thanks! – Columbo Dec 07 '14 at 19:44
For unique_ptr the answer is yes:
The object is destroyed and its memory deallocated when either of the following happens:
- unique_ptr managing the object is destroyed
- unique_ptr managing the object is assigned another pointer via operator= or reset().
The object is destroyed using a potentially user-supplied deleter by calling Deleter(ptr). The deleter calls the destructor of the object and dispenses the memory.
- 154,301
- 39
- 440
- 740