5

Besides all the known benefits of using auto_ptrs, what are auto_ptr "worst-practices"?

  1. Creating STL contrainers of auto_ptrs. auto_ptrs don't fulfill the 'CopyConstructable' requirement. See also Scott Meyer's "Effective STL", item 8.

  2. Creating auto_ptrs of arrays Upon destruction, auto_ptr's destructor uses 'delete' (and never 'delete[]') to destroy the owned object, so this code yields undefined behavior: auto_ptr api(new int[42]);

  3. Not taking care of copy-ctor and op= in a class using auto_ptr members. One might naively think that by using auto_ptr members one doesn't need to implement the copy constructor/assignment operator for a class. However, even a single auto_ptr member 'poisons' a class (i. e. violates the 'CopyConstructable' and 'Assignable' requirements). Objects of such classes would be partly damaged during the copy/assignment operation.

Are there even more auto_ptr pitfalls?

James McNellis
  • 348,265
  • 75
  • 913
  • 977
Ralf Holly
  • 221
  • 1
  • 2
  • Also, `auto_ptr` will be deprecated in the next C++ standard (which Sutter hopes will be officially voted on after March 2011 (http://herbsutter.com/2010/08/28/trip-report-august-2010-iso-c-standards-meeting/), thus becoming C++0B for us die-hards). If you've got `unique_ptr`, use it instead. – David Thornley Sep 01 '10 at 19:33

1 Answers1

6

Not sure if this is a trap/pitfall, but it's certainly less than obvious:

  • A const auto_ptr cannot have its ownership of the contained pointer transferred

In other words:

const auto_ptr<Foo> ap(new Foo());
auto_ptr<Foo> ap2;

ap2 = ap; // Not legal!

This is in fact quite useful if you want to take an auto_ptr argument and guarantee that you won't be taking ownership of the contained pointer, but it can also be surprising if you expect a const auto_ptr<Foo> to behave like a Foo const*.

Tyler McHenry
  • 74,820
  • 18
  • 121
  • 166