auto_ptr<int> pi(new int(1024));
实现代码:
class RealPtr {
friend class AutoPtr;
int *ip;
size_t use;
RealPtr(int *p) : ip(p), use(1) {}
~RealPtr() { delete ip; }
};
class AutoPtr{
public:
AutoPtr(int *p): ptr(new RealPtr(p)) { }
AutoPtr(const AutoPtr &orig) : ptr(orig.ptr) { ++ptr->use; }
AutoPtr& operator=(const AutoPtr& rhs) {
++rhs.ptr->use;
if (--ptr->use == 0) delete ptr;
ptr = rhs.ptr;
return *this;
}
~AutoPtr() { if (--ptr->use == 0) delete ptr; }
int *get_ptr() const { return ptr->ip; }
void set_ptr(int *p) const { ptr->ip = p; }
int get_ptr_val() const { return *ptr->ip; }
void set_ptr_val(int i) { *ptr->ip = i; }
private:
RealPtr *ptr;
};
原文地址:http://blog.csdn.net/u014539401/article/details/45013279