"
auto_ptr
IMPLEMENTATIONauto_ptr
is now available.)
Items 9, 10, 26, 31 and 32 attest to the remarkable utility of the auto_ptr
template. Unfortunately, few compilers currently provide an implementation. Items 9 and 28 sketch how you might write one yourself, but it's nice to have more than a sketch when embarking on real-world projects.
Below are two presentations of a complete implementation for auto_ptr
. The first presentation documents the class interface and implements all the member functions outside the class definition. The second implements each member function within the class definition. Stylistically, the second presentation is inferior to the first, because it fails to separate the class interface from its implementation. However, auto_ptr
is a simple class, and the second presentation brings that out much more clearly than does the first.
Here is auto_ptr
with its interface documented:
template<class T>
class auto_ptr {
public:
explicit auto_ptr(T *p = 0); // see Item 5 for a
// description of ""explicit""template<class U> // copy constructor member
auto_ptr(auto_ptr<U>& rhs); // template (see Item 28):
// initialize a new auto_ptr
// with any compatible
// auto_ptr~auto_ptr();
template<class U>
auto_ptr<T>& operator=(auto_ptr<U>& rhs);
// assignment operator
// member template (see
// Item 28): assign from any
// compatible auto_ptrT& operator*() const; // see Item 28
T* operator->() const; // see Item 28T* get() const; // return value of current
// dumb pointerT* release(); // relinquish ownership of
// current dumb pointer and
// return its valuevoid reset(T *p = 0); // delete owned pointer;
// assume ownership of p
private:
T *pointee;
};template<class T>
inline auto_ptr<T>::auto_ptr(T *p)
: pointee(p)
{}template<class T>
template<class U>
inline auto_ptr<T>::auto_ptr(auto_ptr<U>& rhs)
: pointee(rhs.release())
{}template<class T>
inline auto_ptr<T>::~auto_ptr()
{ delete pointee; }template<class T>
template<class U>
inline auto_ptr<T>& auto_ptr<T>::operator=(auto_ptr<U>& rh"