#include"iostream" using namespace std; //定义一个普通类 class bookClass{ private: string name; int price; public: int getPrice(){ return price; } }; //辅助类 class Counter { private: friend class smartPoint; Counter(bookClass *book) :bk(book), count(1){}; ~Counter(){ delete bk; }; int count; bookClass* bk; }; //智能指针类 class smartPoint { public: smartPoint(bookClass *bkC) :RpCnt(new Counter(bkC)){} smartPoint(const smartPoint &sp) :RpCnt(sp.RpCnt){ ++RpCnt->count; } smartPoint& operator= (const smartPoint& rhs) { ++rhs.RpCnt->count; if (--RpCnt->count == 0) delete RpCnt; RpCnt = rhs.RpCnt; return *this; } ~smartPoint(){ if (--RpCnt->count == 0) delete RpCnt; } private: Counter *RpCnt; };
原文地址:http://blog.csdn.net/tommyzht/article/details/47395385