Auto ptr


auto_ptr is a class template that was available in previous versions of the C++ Standard Library, which provides some basic RAII features for C++ raw pointers. It has been replaced by the unique_ptr class.
The auto_ptr template class describes an object that stores a pointer to a single allocated object that ensures that the object to which it points gets destroyed automatically when control leaves a scope.
The C++11 standard made auto_ptr deprecated, replacing it with the unique_ptr class template. auto_ptr was fully removed in C++17.
For shared ownership, the shared_ptr template class can be used. shared_ptr was defined in C++11 and is also available in the Boost library for use with previous C++ versions.

Declaration

The auto_ptr class is declared in ISO/IEC 14882, section 20.4.5 as:

namespace std

Semantics

The auto_ptr has semantics of strict ownership, meaning that the auto_ptr instance is the sole entity responsible for the object's lifetime. If an auto_ptr is copied, the source loses the reference. For example:

  1. include
  2. include
using namespace std;
int main

This code will print a NULL address for the first auto_ptr object and some non-NULL address for the second, showing that the source object lost the reference during the assignment. The raw pointer i in the example should not be deleted, as it will be deleted by the auto_ptr that owns the reference. In fact, new int could be passed directly into x, eliminating the need for i.
Notice that the object pointed by an auto_ptr is destroyed using operator delete; this means that you should only use auto_ptr for pointers obtained with operator new. This excludes pointers returned by malloc/calloc/realloc, and pointers to arrays.
Because of its copy semantics, auto_ptr may not be used in STL containers that may perform element copies in their operations.