您的位置:首页 > 其它

编写auto_ptr感

2015-07-10 16:47 302 查看
首先,上自己编写的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;
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,其目的是为了防止发生隐式的转换构造函数的调用。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: