Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a contradiction between these two sources about the `auto_ptr` template class?

Tags:

c++

auto-ptr

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 !

like image 224
Belloc Avatar asked Feb 20 '12 11:02

Belloc


1 Answers

Yes, that's definitely a bug in the latter piece of code. Object pointed to by ptr must be deleted before a new value is assigned to ptr, otherwise the object originally pointed to by ptr will be leaked.

like image 134
sharptooth Avatar answered Oct 08 '22 19:10

sharptooth