smart pointer that deletes the instance it points to when going out of scope

View versions (1)

Definition

The auto_ptr class template is defined in the standard header <memory>, and in the nonstandard backward-compatibility header <memory.h>.

template <class Type>
class auto_ptr
ParameterDescription
TypeThe type of object for which storage is being allocated or deallocated

Description

The auto_ptr is provided by the C++ standard library as a kind of a smart pointer that helps to avoid resource leaks when exceptions are thrown.

It manages an object obtained via new and deletes that object when auto_ptr itself is destroyed. It may be used to provide exception safety for dynamically-allocated objects, for passing ownership of dynamically-allocated objects into functions and for returning dynamically-allocated objects from functions.

NOTE:

  • Copying an auto_ptr changes the object being copied by setting the contents to NULL
  • auto_ptr objects are not guaranteed to work correctly with the STL containers

Member Functions

FunctionDescription
(constructor)Creates a new auto_ptr object
(destructor)Destroys an auto_ptr and the managed object
getObtains a pointer to the managed object
operator*Dereference object (accesses the managed object)
operator->Dereference object member (accesses the managed object)
releaseReleases ownership of the managed object
resetDeallocate object pointed and set new value
(conversion operators)Conversion operators

References

Example 1
Problem

The following example of program illustrates how to reset an auto_ptr.

Workings
#include <iostream>
#include <memory>

struct Resetter
{
  Resetter() { std::cout << "Constructor" << std::endl; }
  ~Resetter() { std::cout << "Destructor" << std::endl; }
};

int main()
{
  std::auto_ptr<Resetter> pReset(new Resetter);
  pReset.reset(new Resetter);
}
Solution

Output:

Constructor
Constructor
Destructor
Destructor