//智能指针类
class SmartPt
{
SmartPt(int* p) : pt(p), use(1){}
~SmartPt() {delete pt;}
friend class HasPtr;
int* pt;
size_t use;
};
class HasPtr
{
public:
HasPtr(int* p, int v):ptr(new SmartPt(p)), val(v) {}
HasPtr(const HasPtr& h):ptr(h.ptr), val(h.val) { ++(ptr->use);}
~HasPtr()
{
if (--(ptr->use) < 1)
delete ptr;
}
HasPtr& operator = (const HasPtr& h);
SmartPt* get_ptr() const {return ptr;}
int get_val() const {return val;}
void set_ptr(int* p)
{
ptr->pt = p;
}
void set_val(int v) {val = v;}
int get_ptr_val() const {return *ptr->pt;}
void set_ptr_val(int v) {*ptr->pt = v;}
protected:
private:
SmartPt* ptr;
int val;
};
HasPtr& HasPtr::operator = (const HasPtr& h)
{
++(h.ptr->use);
if (--(ptr->use) == 0)
{
delete ptr;
}
ptr = h.ptr;
val = h.val;
return *this;
}
void testSmartPt(void) //测试函数
{
int* has = new int(12);
HasPtr hasPtr1(has, 42);
HasPtr hasPtr2(hasPtr1);
HasPtr hasPtr3(hasPtr1);
}