编写auto_ptr感
2015-07-10 16:47
302 查看
首先,上自己编写的auto_ptr
下面,上源代码:
其为通过_Owns来设置所有权。在这里注意关键字explicit,其目的是为了防止发生隐式的转换构造函数的调用。
#include<iostream> using namespace std; template<typename T> class my_auto_ptr { public: //构造函数 my_auto_ptr() :ptr(NULL) {} my_auto_ptr(const T *x) :ptr((T *)x) {} //拷贝构造函数 my_auto_ptr(my_auto_ptr &other) { if (&other != this) { if (other.ptr == NULL) ptr = NULL; else { ptr = other.ptr; other.ptr = NULL; } } } //赋值函数重载 my_auto_ptr& operator=(my_auto_ptr &other) { if (&other != this) { if (other.ptr == NULL) ptr = NULL; else ptr = other.ptr; } other.ptr = NULL; return *this; } //运算符的重载 T* operator->() { return ptr; } T& operator*() { return *ptr; } T* get() { return ptr; } ~my_auto_ptr() { if (ptr) delete ptr; } private: T *ptr; bool state; }; int main() { char *str2 = "lianyiming"; char *a = new char[11]; strcpy(a, str2); //无参数构造str my_auto_ptr<char> str; //传参数构造str1 my_auto_ptr<char> str1(a); cout << *str1.get() << endl; //拷贝构造创建,将str1拷贝str3,此时str1变为NULL my_auto_ptr<char> str3(str1); cout << *str3.get() << endl; //赋值实现,将str3赋值传给str,此时str3变为NULL str = str3; cout << *str.get() << endl; return 0; }在这里,我们首先要明白,auto_ptr的作用是用来保存一个指针,且这个指针不能指向对象为数组、类等复杂结构的数据。它的作用是,利用类的析构函数对指针指向的空间实现自动释放。然后,就是对auto_ptr的理解,auto_ptr实现保存一个指针,但不能有多个指针同时指向同一空间。即类似单例模式,一个空间,只允许一个智能指针来使用。
下面,上源代码:
#include<iostream> //#include<memory> using namespace std; //RAII 机制 template<class _Ty> class auto_ptr { public: explicit auto_ptr(_Ty *_P = 0) :_Owns(_P != 0), _Ptr(_P) //_Owns初始化为假 {} auto_ptr(const auto_ptr<_Ty> &_Y) : _Owns(_Y._Owns), _Ptr(_Y.release()) {} auto_ptr<_Ty>& operator=(const auto_ptr<_Ty> &_Y) { if (this != &_Y) { if (_Ptr != _Y.get()) { if (_Owns) { delete _Ptr; _Owns = _Y._Owns; } else if (_Y._Owns) { _Owns = true; _Ptr = _Y.release(); } } } return *this; } ~auto_ptr() { if (_Owns) delete _Ptr; } public: //_Ty*release(const auto_ptr<_Ty> *const this) _Ty* release()const { ((auto_ptr<_Ty> *)this)->_Owns = false; return _Ptr; } _Ty& operator*()const { return (*get()); } _Ty* operator->()const { return(get()); } _Ty* get()const { return _Ptr; } private: bool _Owns; //是否对内存进行释放 真-->释放; 假-->不调用析构 _Ty *_Ptr; }; void main() { auto_ptr<int> ptr; }
其为通过_Owns来设置所有权。在这里注意关键字explicit,其目的是为了防止发生隐式的转换构造函数的调用。
相关文章推荐
- 融云即时通讯集成总结
- JAVA类加载和反射介绍
- javascript 原生态 checkbox 操作
- 常见的内存错误以及如何避免
- eclipse android 设置及修改生成apk的debug签名文件
- leetcode-53-Maximum Subarray
- codeforces #304 546 C. Soldier and Cards() (模拟)
- Windows 增强版任务管理器-Process Explorer
- Object-c的继承、封装、多态
- 运算符重载
- Linux访问Windows磁盘实现共享
- 修改cas-server(二),修改认证方式为jdbc。
- 黑马程序员 异常( 格式 体现 总结 ) 包
- 黑马程序员--内部类
- JQuery 提供了两种方式来阻止事件冒泡及区别
- JQuery 提供了两种方式来阻止事件冒泡及区别
- JQuery 提供了两种方式来阻止事件冒泡及区别
- JQuery 提供了两种方式来阻止事件冒泡及区别
- JQuery 提供了两种方式来阻止事件冒泡及区别
- HDU -- 4280 Island Transport(最大流)