编写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;
            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,其目的是为了防止发生隐式的转换构造函数的调用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值