标签:智能指针
// vc下的智能指针,重点在于拥有权的转移 #include <iostream> using namespace std; template<class Type> class Autoptr { public: Autoptr(int *p = NULL) :ptr(p), owns(ptr != NULL) {} Autoptr(const Autoptr<Type> &t) :ptr(t.release()), owns(t.owns) {} Autoptr<Type>& operator=(const Autoptr<Type> &t) { if (this != &t)// 判断是否给自己赋值 { if (ptr != t.ptr)// 判断是否指向同一个空间 { if (owns)// 如果有拥有权,则释放当前空间 { delete ptr; } else { owns = t.owns;// 反之,得到拥有权 } ptr = t.release();// 让t失去拥有权 } } return *this; } ~Autoptr() { if (owns) delete ptr; } public: Type& operator*()const { return (*get()); } Type* operator->()const { return get(); } Type* get()const { return ptr; } Type* release()const { ((Autoptr<Type> *const)this)->owns = false; return ptr; } private: bool owns; Type *ptr; }; int main() { int *p = new int(10); Autoptr<int> pa(p); cout << *pa << endl; Autoptr<int> pa1(pa); cout << *pa1 << endl; int *p1 = new int(100); Autoptr<int> pa2(p1); Autoptr<int> pa3; pa3 = pa2; cout << *pa3 << endl; return 0; }
标签:智能指针
原文地址:http://blog.csdn.net/zhaoyaqian552/article/details/46381609