This site states on "Ownership, Sources, and Sinks" :
"When you copy an auto_ptr
, you automatically transfer ownership from the source auto_ptr
to the target auto_ptr
; if the target auto_ptr
already owns an object, that object is first freed. After the copy, only the target auto_ptr
owns the pointer and will delete it in due time, while the source is set back to a null state and can no longer be used to refer to the owned object.".
Now consider the definition of operator=()
for the templacte<classX> class auto_ptr
, in Chapter 14, page 368 of Stroustrup's The C++ Programming Language Third Edition:
auto_ptr& operator=(auto_ptr& a) throw() { ptr = a.ptr; a.ptr = 0; }
I can't see the operator freeing the object addressed by ptr
, in case ptr != 0
!
Yes, that's definitely a bug in the latter piece of code. Object pointed to by ptr
must be delete
d before a new value is assigned to ptr
, otherwise the object originally pointed to by ptr
will be leaked.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With