TITLE: What is auto_ptr? [ This was part of a discussion about the "resource initialization is acquistion" idiom used when programming with exceptions. -adc ] PROBLEM: clarke@ses.com, 26 May 95 I missed your post on using "auto_ptr" for conditionals and constructors. Can you give me a hint as to its implementation? RESPONSE: kanze@gabi-soft.fr (J. Kanze) It's a proposed standard class, so you should get it sometime (soon?) with your compiler. In the meantime, it is fairly simple to implement: ------------------------------------------------------------------------ template< class T > class auto_ptr { public : auto_ptr( T* p = 0 ) ; auto_ptr( auto_ptr const& other ) ; void operator=( auto_ptr const& other ) ; ~auto_ptr() ; T* get() const ; T& operator*() const ; T* operator->() const ; T* release() ; T* reset( T* p = 0 ) ; private : T* ptr ; } ; template< class T > auto_ptr< T >::auto_ptr( T* p ) : ptr( p ) { } template< class T > auto_ptr< T >::auto_ptr( auto_ptr const& other ) : ptr( other.release() ) { } template< class T > void auto_ptr< T >::operator=( auto_ptr const& other ) { reset( other.release() ) ; } template< class T > auto_ptr< T >::~auto_ptr() { delete ptr ; } template< class T > T* auto_ptr< T >::get() const { return ptr ; } template< class T > T& auto_ptr< T >::operator*() const { return *get() ; } template< class T > T* auto_ptr< T >::operator->() const { return get() ; } template< class T > T* auto_ptr< T >::release() { T* tmp = ptr ; ptr = 0 ; return tmp ; } template< class T > T* auto_ptr< T >::reset( T* p ) { delete ptr ; ptr = p ; } ------------------------------------------------------------------------ The above is just a quick sketch. I wrote this for myself, with the intention of shifting over to auto_ptr (since it is part of the standard) from the techniques I previously used. But I haven't had time to actually test it, or even compile it, yet. Still, the principle should be evident. Ownership of a pointer resides in one (and only one) auto_ptr, whose destructor deletes the object. Copying and assignment transfer ownership. And the pointer only works if it owns something. (I might add that this section (20.4.5) in the current draft was obviously written in haste, and needs some serious rewriting.)