本文主要是介绍编写auto_ptr感,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
首先,上自己编写的auto_ptr
#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;elseptr = 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);//无参数构造strmy_auto_ptr<char> str;//传参数构造str1my_auto_ptr<char> str1(a);cout << *str1.get() << endl;//拷贝构造创建,将str1拷贝str3,此时str1变为NULLmy_auto_ptr<char> str3(str1);cout << *str3.get() << endl;//赋值实现,将str3赋值传给str,此时str3变为NULLstr = 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,其目的是为了防止发生隐式的转换构造函数的调用。
这篇关于编写auto_ptr感的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!