码迷,mamicode.com
首页 > 编程语言 > 详细

【C++】智能指针的实现

时间:2015-08-08 20:00:08      阅读:132      评论:0      收藏:0      [点我收藏+]

标签:c++   stl   智能指针   

一点都不智能的智能指针

#include <iostream>
using namespace std;

template<typename T>
class Auto
{
public:
	// 避免编译器报错,需要显式类型转换
	explicit Auto(T* data = NULL) : m_data(data) {}

	// 转移拷贝
	Auto(Auto<T>& that) : m_data(change(that)) {}

	// 转移赋值
	Auto& operator = (Auto<T>& that)
	{
		if (this != &this)
			return release(change(that));
		return *this;
	}

	~Auto(void)
	{
		delete m_data;
	}

	T& operator * (void)
	{
		return *m_data;
	}

	T const& operator * (void) const
	{
		return *(const_cast<Auto&>(*this));
	}

	T* operator -> (void)
	{
		return m_data;
	}

	T *const operator ->(void) const
	{
		return m_data;
	}

	friend ostream& operator << (ostream& os, Auto const& rhs)
	{
		return os << rhs.m_data;
	}

private:
	T* change(Auto<T>& that)
	{
		T* temp = that.m_data;
		that.m_data = NULL;
		return temp;
	}
	Auto& release(T* data)
	{
		delete m_data;
		m_data = data;
		return *this;
	}

	T* m_data;
};

// 特化数组类型的
template<typename T>
class Auto<T[]>
{
public:
	explicit Auto(T* data = NULL) : m_data(data) {}

	Auto(Auto<T>& that) : m_data(change(that)) {}

	Auto& operator = (Auto<T>& that)
	{
		if (that != *this)
			return release(change(that));
		return *this;
	}

	~Auto(void)
	{
		delete[] m_data;
	}


	T& operator * (void)
	{
		return *m_data;
	}

	T const& operator * (void) const
	{
		return *(const_cast<Auto&>(*this));
	}

	T* operator -> (void)
	{
		return m_data;
	}

	T *const operator ->(void) const
	{
		return m_data;
	}

	friend ostream& operator << (ostream& os, Auto const& rhs)
	{
		return os << rhs.m_data;
	}

private:
	T* change(Auto<T>& that)
	{
		T* temp = that.m_data;
		that.m_data = NULL;
		return temp;
	}
	Auto& release(T* data)
	{
		delete m_data;
		m_data = data;
		return *this;
	}

	T* m_data;
};


版权声明:本文为博主原创文章,未经博主允许不得转载。

【C++】智能指针的实现

标签:c++   stl   智能指针   

原文地址:http://blog.csdn.net/qq_26369213/article/details/47360947

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!