// 智能指针 // 作用: // 1. 管理堆内存 // 使用约束: // 1. 不能将智能指针对象赋值给智能指针对象 // 2. 不能将栈对象取地址后赋值给智能指针 // 3. 每一个对应的堆对象地址只能赋值给一个智能指针对象 #pragma once template<class T> class CSmartPoint { unsigned int count; T* p; public: CSmartPoint() { count = 1; p = NULL; } ~CSmartPoint() { count--; if (p && count == 0) { delete p; p = NULL; } } CSmartPoint(T* pt) { count = 1; if (p) { delete p; } p = pt; } CSmartPoint(const CSmartPoint& sp) { p = sp.p; count = sp.count + 1; } T* get() { return p; } CSmartPoint& operator=(T* pt) { if (p == pt) { return *this; } if (p) { delete p; } p = pt; return *this; } T* operator->() { return p; } };
原文地址:http://www.cnblogs.com/acnwcl/p/3853875.html