Shared_ptr的实现

https://blog.csdn.net/albertsh/article/details/82286999(讲的比较好的智能指针的文章)

#include

///

//

// template class shared_ptr

// 2004-6-12

// Chengliang Shan

// simouse@126.com

//

///

#ifndef SHARED_PTR_H_

#define SHARED_PTR_H_

namespace clshan {

template<class T>

class shared_ptr;



template<class T>

class shared_data

{

private:

	friend class shared_ptr<T>;



	explicit shared_data(T* pT) :_M_ptr(pT) {

		_M_nCount = 1;

	}



	~shared_data() {

		delete _M_ptr;

	}



	void operator++ () {

		++_M_nCount;

	}



	operator-- () {

		--_M_nCount;

		if (_M_nCount == 0) {

			delete this;

		}

	}



	T& operator* () const {

		return *_M_ptr;

	}



	T* operator-> () const {

		return _M_ptr;

	}



	bool operator== (T* pT) const {

		return _M_ptr == pT;

	}



	T* get() {

		return _M_ptr;

	}



	int use_count() {

		return _M_nCount;

	}



private:

	T* _M_ptr;

	unsigned int _M_nCount;

};



template<class T>

class shared_ptr

{

	typedef shared_data<T> element;

public:

	explicit shared_ptr(T* pT) :_M_pD(NULL) {

		_M_pD = new element(pT);

	}



	explicit shared_ptr() :_M_pD(NULL) {

	}



	// copy constructor

	shared_ptr(const shared_ptr<T>& rT) {

		_M_pD = rT.get_element();

		if (_M_pD != NULL) {

			++(*_M_pD);

		}

	}



	~shared_ptr() {

		if (_M_pD != NULL) {

			--(*_M_pD);

		}

	}



	// assignment operator

	shared_ptr<T>& operator = (shared_ptr<T>& rT) {

		if (_M_pD != NULL) {

			--(*_M_pD);

		}

		_M_pD = rT.get_element();

		if (_M_pD != NULL) {

			++(*_M_pD);

		}

		return *this;

	}



	T& operator* () const {

		return _M_pD->operator *();

	}



	T* operator-> () const {

		return _M_pD->operator ->();

	}



	bool operator== (shared_ptr<T>& rT) const {

		return rT.get_element() == _M_pD;

	}



	bool operator== (T* pT) const {

		if (_M_pD == NULL) {

			return pT == NULL;

		}

		return *_M_pD == pT;

	}



	T* get() {

		if (_M_pD == NULL) {

			return NULL;

		}

		else {

			return _M_pD->get();

		}

	}



	void release() {

		if (_M_pD != NULL) {

			--(*_M_pD);

			_M_pD = NULL;

		}

	}



	void reset(T* pT) {

		if (_M_pD != NULL) {

			--(*_M_pD);

			_M_pD = NULL;

		}

		_M_pD = new element(pT);

	}



private:

	element* get_element()const {

		return _M_pD;

	}



	element* _M_pD;

};

}

#endif

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值