Top of document
©Copyright 1999 Rogue Wave Software

auto_ptr


     Memory Management

Summary

A simple, smart pointer class.

Contents

Synopsis

#include <memory>
template <class X> class auto_ptr;

Description

The template class auto_ptr holds onto a pointer obtained via new and deletes that object when the auto_ptr object itself is destroyed (such as when leaving block scope). auto_ptr can be used to make calls to operator new exception-safe. The auto_ptr class provides semantics of strict ownership: an object may be safely pointed to by only one auto_ptr, so copying an auto_ptr copies the pointer and transfers ownership to the destination.

Interface

template <class X> class auto_ptr {
   public:
     // constructor/copy/destroy
     explicit auto_ptr (X* = 0);
     auto_ptr (const auto_ptr<X>&);
     void operator= (const auto_ptr<X>&);
     ~auto_ptr ();
     // members
     X& operator* () const;
     X* operator-> () const;
     X* get () const;
     X* release ();
     void reset (X* = 0);
 };

Constructors and Destructors

explicit 
auto_ptr (X* p = 0);
auto_ptr (const auto_ptr<X>& a);
~auto_ptr ();

Operators

void 
operator= (const auto_ptr<X>& a);
X& 
operator* () const;
X* 
operator-> () const;

Member Functions

X* 
get () const;
X*
release();
void 
reset (X* p = 0);

Example

   //
   // auto_ptr.cpp
   //
   #include <iostream.h>
   #include <memory>
   //
   // A simple structure.
   //
   struct X
   {
       X (int i = 0) : m_i(i) { }
       int get() const { return m_i; }
       int m_i;
   };
   int main ()
   {
      //
      // b will hold a pointer to an X.
      //
      auto_ptr<X> b(new X(12345));
      //
      // a will now be the owner of the underlying pointer.
      //
      auto_ptr<X> a = b;
      //
      // Output the value contained by the underlying pointer.
      //
      cout << a->get() << endl;
      //
      // The pointer will be deleted when a is destroyed on 
      // leaving scope.
      //
      return 0;
   }
Output : 
12345

Top of document