【c++】智能指针
2015-06-05 20:50
645 查看
// 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; }
相关文章推荐
- C++的继承与接口
- C++的继承与接口
- C++ 多继承和虚继承的内存布局
- C++对象析构函数解析示例
- 【学习笔记】【C语言】逗号运算符
- C语言中内存对齐问题
- C++ 中dynamic_cast<>的使用方法
- 【c++类与对象练习】判断字符串str是否为当前串的子串
- 如何在VS2013中配置一个DirectX开发环境
- 【c++】引用计数
- C++程序设计 - Week 5 继承与派生
- C语言中 内存的申请与释放
- MFC LNK 2005错误
- vs2010中点击新建项,为c++头文件和cpp文件,添加文件头注释
- C语言字符串函数大全
- 【c++】浅拷贝成功__count解决
- C++的字符串分割函数
- c++11新特性for循环
- Python C++扩展
- c++类中特殊数据类型成员变量的初始化