In the C++ programming language, (for automatic pointer) is an obsolete smart pointer class template that was available in previous versions of the C++ standard library (declared in the <code><memory></code> header file), which provides some basic RAII features for C++ raw pointers. It has been replaced by the <code>unique_ptr</code> class.
The <code>auto_ptr</code> 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 characteristics of <code>auto_ptr</code> are now considered unsatisfactory: it was introduced before C++11's move semantics, so it uses copying for what should be done with moves (and confusingly sets the copied-from <code>auto_ptr</code> to a null pointer). These copy semantics mean that it cannot be used in STL containers.
The C++11 standard made <code>auto_ptr</code> deprecated, replacing it with the <code>unique_ptr</code> class template. <code>auto_ptr</code> was fully removed in C++17. For shared ownership, the <code>shared_ptr</code> template class can be used. <code>shared_ptr</code> was defined in C++11 and is also available in the Boost library for use with previous C++ versions.
The <code>auto_ptr</code> class is declared in ISO/IEC 14882, section 20.4.5 as:
The <code>auto_ptr</code> has semantics of strict ownership, meaning that the <code>auto_ptr</code> instance is the sole entity responsible for the object's lifetime. If an <code>auto_ptr</code> is copied, the source loses the reference. For example:
This code will print a NULL address for the first <code>auto_ptr</code> object and some non-NULL address for the second, showing that the source object lost the reference during the assignment (<code>=</code>). The raw pointer <code>i</code> in the example should not be deleted, as it will be deleted by the <code>auto_ptr</code> that owns the reference. In fact, <code>new int</code> could be passed directly into <code>x</code>, eliminating the need for <code>i</code>.
Notice that the object pointed by an <code>auto_ptr</code> is destroyed using <code>operator delete</code>; this means that you should only use <code>auto_ptr</code> for pointers obtained with <code>operator new</code>. This excludes pointers returned by <code>malloc/calloc/realloc</code>, and pointers to arrays (because arrays are allocated by <code>operator new[]</code> and must be deallocated by <code>operator delete[]</code>).
Because of its copy semantics, <code>auto_ptr</code> may not be used in STL containers that may perform element copies in their operations.