Auto ptr

In the C++ programming language, auto_ptr is an obsolete smart pointer class template that was available in previous versions of the C++ standard library (declared in the  header file), which provides some basic RAII features for C++ raw pointers. It has been replaced by the  class.

The  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  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   to a NULL pointer). These copy semantics mean that it cannot be used in STL containers.

The C++11 standard made  deprecated, replacing it with the   class template. was fully removed in C++17. For shared ownership, the  template class can be used. was defined in C++11 and is also available in the Boost library for use with previous C++ versions.

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

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

This code will print a NULL address for the first  object and some non-NULL address for the second, showing that the source object lost the reference during the assignment. The raw pointer  in the example should not be deleted, as it will be deleted by the   that owns the reference. In fact,  could be passed directly into , eliminating the need for.

Notice that the object pointed by an  is destroyed using  ; this means that you should only use   for pointers obtained with. This excludes pointers returned by, and pointers to arrays (because arrays are allocated by   and must be deallocated by  ).

Because of its copy semantics,  may not be used in STL containers that may perform element copies in their operations.