代码:
#include "stdio.h"
// auxiliary type to enable copies and assignments (now global)
template<class Y>
struct auto_ptr_ref {
Y* yp;
auto_ptr_ref (Y* rhs)
: yp(rhs)
{
printf("auto_ptr_ref::auto_ptr_ref(Y* rhs)\n");
}
};
template<class T>
class auto_ptr {
private:
T* ap; // refers to the actual owned object (if any)
public:
typedef T element_type;
// constructor
explicit auto_ptr (T* ptr = 0) throw()
: ap(ptr)
{
printf("explicit auto_ptr::auto_ptr (T* ptr)\n");
}
// copy constructors (with implicit conversion)
// - note: nonconstant parameter
auto_ptr (auto_ptr& rhs) throw()
: ap(rhs.release())
{
printf("auto_ptr::auto_ptr(auto_ptr& rhs)\n");
}
template<class Y>
auto_ptr (auto_ptr<Y>& rhs) throw()
: ap(rhs.release())
{
printf("auto_ptr::auto_ptr(auto_ptr<Y>& rhs)\n");
}
// assignments (with implicit conversion)
// - note: nonconstant parameter
auto_ptr& operator= (auto_ptr& rhs) throw()
{
printf("auto_ptr::operator= (auto_ptr& rhs)\n");
reset(rhs.release());
return *this;
}
template<class Y>
auto_ptr& operator= (auto_ptr<Y>& rhs) throw()
{
printf("auto_ptr::operator= (auto_ptr<Y>& rhs)\n");
reset(rhs.release());
return *this;
}
// destructor
~auto_ptr() throw()
{
printf("auto_ptr::~auto_ptr()\n");
delete ap;
}
// value access
T* get() const throw() {
return ap;
}
T& operator*() const throw() {
return *ap;
}
T* operator->() const throw() {
return ap;
}
// release ownership
T* release() throw() {
T* tmp(ap);
ap = 0;
return tmp;
}
// reset value
void reset (T* ptr=0) throw() {
if (ap != ptr) {
delete ap;
ap = ptr;
}
}
/* special conversions with auxiliary type to enable copies and assignments
*/
auto_ptr(auto_ptr_ref<T> rhs) throw()
: ap(rhs.yp)
{
printf("auto_ptr(auto_ptr_ref<T> rhs)\n");
}
auto_ptr& operator= (auto_ptr_ref<T> rhs) throw()
{ // new
printf("auto_ptr& operator= (auto_ptr_ref<T> rhs)\n");
reset(rhs.yp);
return *this;
}
template<class Y>
operator auto_ptr_ref<Y>() throw()
{
printf("auto_ptr::operator auto_ptr_ref<Y>()\n");
return auto_ptr_ref<Y>(release()
);
}
template<class Y>
operator auto_ptr<Y>() throw()
{
printf("auto_ptr::operator auto_ptr<Y>()\n");
return auto_ptr<Y>(release());
}
};
auto_ptr<int> foo1()
{
auto_ptr<int> p=auto_ptr<int>(new int(1));
return p;
// return auto_ptr<int>(new int(1));
}
int main()
{
auto_ptr<int> i(foo1());
}
the code is copied from NicolaiM. Josuttis's book.
I just added couple printf to show myself the execution path.
The running result is
代码:
explicit auto_ptr::auto_ptr (T* ptr)
auto_ptr::operator auto_ptr_ref<Y>()
auto_ptr_ref::auto_ptr_ref(Y* rhs)
auto_ptr(auto_ptr_ref<T> rhs)
auto_ptr::~auto_ptr()
auto_ptr::operator auto_ptr_ref<Y>()
auto_ptr_ref::auto_ptr_ref(Y* rhs)
auto_ptr(auto_ptr_ref<T> rhs)
auto_ptr::~auto_ptr()
auto_ptr::~auto_ptr()
My Question is: why these are two lines of
auto_ptr:

perator auto_ptr_ref<Y>()
I can only understand the first call to auto_ptr:

perator auto_ptr_ref<Y>(), but not the second one.
Thanks for help!