8

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 !

sbi
  • 219,715
  • 46
  • 258
  • 445
Belloc
  • 6,318
  • 3
  • 22
  • 52

1 Answers1

4

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.

sharptooth
  • 167,383
  • 100
  • 513
  • 979
  • Curiously, even in the errata (http://www2.research.att.com/~bs/3rd_printing5.html) the deletion is not mentioned. – Belloc Feb 20 '12 at 12:14
  • 1
    @sharptooth: especially unused code bases - it's not as if the code in C++PL is being automatically extracted from the repository of a production implementation of `auto_ptr`. – Steve Jessop Feb 20 '12 at 12:30