智能指针的使用栗子(如下定义中,也可以将指针计数维护类增加封装为友元类):
// CMySmartPtr指针封装类,将普通指针封装为智能指针 template <class T> class CMySmartPtr { public: /* 构造函数 */ CMySmartPtr(T* pT) { pCountT = new CCountT(pT); } CMySmartPtr() { pCountT = NULL; // 默认指针为空 } /* 复制控制 */ ~CMySmartPtr() { DeleteData(); } CMySmartPtr(const CMySmartPtr& p) { CopyData(p); } CMySmartPtr& operator=(const CMySmartPtr& p) { if (this != &p) // 注意自身对自身赋值的情况 { DeleteData(); CopyData(p); } return *this; } /* 指针*和->解引用 */ T& operator*() { return *(this->pCountT->pT); } T* operator->() { return this->pCountT->pT; } private: // 装饰类,为智能指针维护引用计数、和所管理类型的指针 class CCountT { public: CCountT(T* pT) { this->pT = pT; this->nCount = 1; } ~CCountT() { delete pT; } T* pT; int nCount; }; // 统一共享的指针,依靠引用计数来释放 private: CCountT *pCountT; void CopyData(const CMySmartPtr& p) { p.pCountT->nCount++; this->pCountT = p.pCountT; } void DeleteData() { if (pCountT && --pCountT->nCount==0) { delete pCountT; pCountT = NULL; } } };