A Problem with Pointers





What is auto_ptr?





Basic auto_ptr Syntax

#include <memory> ... auto_ptr<int> p1(new int) ; // standard init auto_ptr<int> p2(p1) ; // change of ownership auto_ptr<int> p3 ; // not initialized int n = *p2 ; // dereference auto_ptr<string> p4(new string("foobar")) ; int length = p4->size() ;



Some auto_ptr Details





Some auto_ptr Methods





Exceptions and pointers

// Some exception unsafe code void foobar( ) { Fred *pFred = new Fred; try { // call some function of Fred // an exception might be thrown } catch( ... ) { // for all exceptions throw; // rethrow to higher level } delete pFred; }



Exceptions and auto_ptr

// Some safer code void foobar( ) { auto_ptr<Fred> apFred(new Fred); try { // call some function of Fred // an exception might be thrown } catch( ... ) { // for all exceptions throw; // rethrow to higher level } }