Auto Ptr Article Index for
Auto
Website Links For
Auto
 

Information About

Auto Ptr




auto_ptr is a Template class available in the C++ Standard Library (declared in '''''') that provides some basic RAII features for C++ Raw Pointers .


DEFINITION

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

namespace std {

template struct auto_ptr_ref {};


template
class auto_ptr {
public:
typedef X element_type;

// 20.4.5.1 construct/copy/destroy:
  • p =0) throw();

  • auto_ptr(auto_ptr&) throw();

template auto_ptr(auto_ptr&) throw();

auto_ptr& operator=(auto_ptr&) throw();
template auto_ptr& operator=(auto_ptr&) throw();
auto_ptr& operator=(auto_ptr_ref r) throw();

~auto_ptr() throw();

// 20.4.5.2 members:
  • () const throw();

  • operator->() const throw();

  • get() const throw();

  • release() throw();

  • p =0) throw();


// 20.4.5.3 conversions:
auto_ptr(auto_ptr_ref) throw();
template operator auto_ptr_ref() throw();
template operator auto_ptr() throw();
};

}


SEMANTICS

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

  • i = new int;

  • auto_ptr x(i);

auto_ptr y;

y = x;

cout << x.get() << endl;
cout << y.get() << endl;

This code will print a NULL reference for the first auto_ptr object and some 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.

Notice that the object pointed by an auto_ptr is destructed 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 ''operator new {Link without Title} ''.