标签:
// 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://www.cnblogs.com/mengfanrong/p/5136444.html