实现智能指针shared_ptr

#include 
#include 
using namespace std;

template
class SmartPtr
{
private:
	T* _ptr;
	int* use_count; 

public:
	//构造函数
	SmartPtr(T* ptr = nullptr) :_ptr(ptr)
	{
		if (_ptr){
			use_count = new int(1);
		}
		else{
			use_count = new int(0);
		}
	}

	//拷贝构造
	SmartPtr(const SmartPtr& rhs)
	{
		if (this != &rhs){
			this->_ptr = rhs._ptr;
			this->use_count = rhs.use_count;

			(*this->use_count)++;
		}
	}

	//重载operator=
	SmartPtr& operator=(const SmartPtr& rhs)
	{
		if (this->_ptr == rhs._ptr){
			return *this;
		}
		if (this->_ptr){
			(*this->use_count)--;
			if (this->use_count == 0){
				delete this->_ptr;
				delete this->use_count;
			}
		}
		this->_ptr = rhs._ptr;
		this->use_count = rhs.use_count;
		(*this->use_count)++;
		return *this;
	}

	//重载operator*
	T& operator*()
	{
		if (this->_ptr){
			return *(this->_ptr);
		}
	}

	//重载operator->
	T* operator->()
	{
		if (this->_ptr){
			return this->_ptr;
		}
	}

	//析构函数
	~SmartPtr()
	{
		(*this->use_count)--;
		if (*this->use_count == 0){
			delete this->_ptr;
			delete this->use_count;
		}
	}

	//返回计数
	int get_count()
	{
		return *this->use_count;
	}
};

int main()
{
	SmartPtr sm(new int(10));
	cout << "operator*():" << *sm << endl;
	cout << "reference counting:(sm)" << sm.get_count() << endl;
	{
		SmartPtr sm2(sm);
		cout << "copy ctor reference counting:(sm)" << sm.get_count() << endl;
		SmartPtr sm3;
		sm3 = sm;
		cout << "copy operator= reference counting:(sm)" << sm.get_count() << endl;
		cout << &sm << endl;
	}
	cout << "reference counting:(sm)" << sm.get_count() << endl;
	return 0;
}

测试结果:

实现智能指针shared_ptr_第1张图片

 

 

你可能感兴趣的:(C/C++)