Template Class auto_ptr

The auto_ptr class stores a pointer to an object obtained using new and deletes that object when it is destroyed. For example when a local allocation goes out of scope.

The template auto_ptr_ref holds a reference to an auto_ptr, and is used by the auto_ptr conversions. This allows auto_ptr objects to be passed to and returned from functions.

Note: An auto_ptr owns the object it holds a pointer to. When copying an auto_ptr the pointer transfers ownership to the destination.

If more than one auto_ptr owns the same object at the same time the behavior of the program is undefined.

See the example of using std::auto_ptr and extension version for arrays in Using Auto_ptr

This extension can be turned on by uncommenting the statement,

#define _EWL_ARRAY_AUTO_PTR in <ewlconfig>. No recompile of the C++ lib is necessary, but do rebuild any precompiled headers when making this change.

The functionality provided by the extended std::auto_ptr is very similar to that provided by the newer Metrowerks::alloc_ptr found in <ewl_utility>.

Listing: Using Auto_ptr
#include <iostream>
#include <memory>

using std::auto_ptr;

using std::_Array;

struct A

{

   A() {std::cout << "construct A\n";}

   virtual ~A() {std::cout << "destruct A\n";}

};

struct B

   : A

{

   B() {std::cout << "construct B\n";}

   virtual ~B() {std::cout << "destruct B\n";}

};

auto_ptr<B> source();

void sink_b(auto_ptr<B>);

void sink_a(auto_ptr<A>);

auto_ptr<B, _Array<B> > array_source();

void array_sink(auto_ptr<B, _Array<B> >);

auto_ptr<B>

source()

{

   return auto_ptr<B>(new B);

}

void

sink_b(auto_ptr<B>)

{

}

 

void

sink_a(auto_ptr<A>)

{

}

auto_ptr<B, _Array<B> >

array_source()

{

   return auto_ptr<B, _Array<B> >(new B [2]);

}

void

array_sink(auto_ptr<B, _Array<B> >)

{

}

int main()

{

   {

      auto_ptr<B> b(new B);

      auto_ptr<B> b2(b);

      b = b2;

      auto_ptr<B> b3(source());

      auto_ptr<A> a(b);

      a = b3;

      b3 = source();

      sink_b(source());

      auto_ptr<A> a2(source());

      a2 = source();

      sink_a(source());

   }

   {

      auto_ptr<B, _Array<B> > b(new B [2]);

      auto_ptr<B, _Array<B> > b2(b);

      b = b2;

      auto_ptr<B, _Array<B> > b3(array_source());

      b3 = array_source();

      array_sink(array_source());

//      auto_ptr<A, _Array<A> > a(b3);   // Should not compile

//      a = b3;                                     // Should not 
compile

   }

}