C++实现智能指针

#include <iostream>
#include <memory>
using namespace std;

// 智能指针自我实现
template <typename T>
class MyAutoPtr
{
private:
	T * _ptr;
	int * _count;
public:
	MyAutoPtr(T* pt = nullptr) :_ptr(pt)
	{
		if (_ptr)
			_count = new int(1);
		else
			_count = new int(0);
	}
	MyAutoPtr(const MyAutoPtr& ptr)
	{
		_ptr = ptr._ptr;
		_count = ptr._count;
		(*_count)++;
	}
	MyAutoPtr& operator=(const MyAutoPtr& ptr)
	{
		if (this->_ptr == ptr._ptr) // 对地址做比较
		{
			return *this;
		}
		if (this->_ptr)
		{
			(*this->_count)--;
			if (*this->_count == 0)
			{
				delete this->_ptr;
				this->_ptr = nullptr;
			}
		}
		this->_ptr = ptr._ptr;
		this->_count = ptr._count;
		(*this->_count)++;
		return *this;
	}
	~MyAutoPtr()
	{
		--(*this->_count);
		if (this->_count == 0)
		{
			delete this->_ptr;
			delete this->_count;
		}
	}
	T* operator->()
	{
		//assert(this->_ptr == nullptr); // 如果其值为假(即为0),那么它先向stderr打印一条出错信息,然后通过调用 abort 来终止程序运行。
		return this->_ptr;
	}
	T& operator*()
	{
		//assert(this->_ptr == nullptr); // 如果其值为假(即为0),那么它先向stderr打印一条出错信息,然后通过调用 abort 来终止程序运行。
		return *(this->_ptr);
	}
	int get_count()
	{
		return *this->_count;
	}
};

void main()
{
	int * p = new int(23);
	MyAutoPtr<int> p1(p);
	MyAutoPtr<int> p2(new int(13));
	MyAutoPtr<int> p3;
	p3 = p2;
	cout << p1.get_count() << endl;
	cout << p2.get_count() << endl;
	cout << p3.get_count() << endl;
}

程序运行结果:

1
2
2

由于智能指针指向的对象可能同时也被其它的指针指向,因此智能指针类内增加一个count成员用来表示当前被指向的对象一共有多少个指针正在指向它。

发布了8 篇原创文章 · 获赞 1 · 访问量 26

猜你喜欢

转载自blog.csdn.net/qq_43479736/article/details/105082582