liveBook · Manning

Auto_ptr

As explained in 100 C++ Mistakes and How to Avoid Them

std::auto_ptr was a deprecated and removed C++ standard-library smart pointer with transfer-on-copy ownership behavior.

std::auto_ptr was a deprecated and removed standard-library smart pointer whose transfer-on-copy ownership made ordinary copying surprising. It aimed to simplify raw-pointer resource management, but its exclusive ownership conflicted with container requirements and complicated maintenance. section 10.6 section 6.7

The practical mistakes fall into two related cases:

  • Putting auto_ptr objects in a standard container fails because container elements must be copy constructible and assignable, while auto_ptr is neither. section 6.7
  • Using auto_ptr for individual resources reduces explicit cleanup and handles destruction during exception paths, but its unusual ownership behavior makes the type a poor long-term choice. section 10.6
  • For polymorphic collections, a vector of base objects slices derived data; the auto_ptr workaround still does not provide a usable container solution. section 6.7

A safer direction for legacy code

A resource held by std::auto_ptr can be rewritten with a scoped ownership wrapper such as boost::scoped_ptr, which preserves automatic cleanup without the same transfer-on-copy behavior. For polymorphic collections, the demonstrated correction stores Person* values and invokes virtual functions through those pointers; ownership and lifetime must then be reviewed carefully. Modern code should prefer a current ownership type such as std::unique_ptr rather than introducing auto_ptr.

How 100 C++ Mistakes and How to Avoid Them covers it

How deep it goes
Explains ownership semantics, container incompatibility, exception cleanup, and migration examples without detailing the implementation internals.
Examples
Demonstrates failed vector insertion, sliced Person objects, exception cleanup for Student resources, and scoped or unique ownership replacements.
What it assumes
Assumes familiarity with pointers, dynamic allocation, inheritance, virtual functions, containers, and exceptions.
What you can do after
Diagnose/debug auto_ptr container failures and replace simple ownership cases with scoped or unique ownership while reviewing legacy lifetimes.
How it connects
Connects auto_ptr to smart pointers, RAII, raw pointers, standard containers, polymorphism, object slicing, scoped_ptr, and unique_ptr.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 C++ Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.