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

1

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 !

Extravaganza answered 20/2, 2012 at 11:56 Comment(3)
Something else suspicious: that operator= isn't returning anything.Londoner
@sbi The C++ Programming Language Third EditionExtravaganza
What's the type of ptr? Is that classX* or auto_ptr_guts<classX> ? If it's the latter, the code above would be fairly trivial.Cousins
M
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.

Maxilliped answered 20/2, 2012 at 12:1 Comment(2)
Curiously, even in the errata (www2.research.att.com/~bs/3rd_printing5.html) the deletion is not mentioned.Extravaganza
@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.Airhead

© 2022 - 2024 — McMap. All rights reserved.