手寫智能指針(shared_ptr)

純粹是個人實現,可能有錯誤,還請海涵。。

我只實現了基本的功能和use_count函數,實現其他像swap,reset函數並未做實現。

直接上代碼吧。

這是模板類的實現

//智能指針的實現

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

template<class T>
class MyShared_ptr
{
public:

	//構造函數
	explicit MyShared_ptr(T *p = NULL)
	{
		this->m_ptr = p;
		this->m_count = new size_t;
		if (p == NULL)
		{
			*this->m_count = 0;
		}
		else
		{
			*this->m_count = 1;
		}
	}

	//析構函數
	~MyShared_ptr()
	{
		if (this->m_ptr)
		{
			if (*(--this->m_count) == 0)
			{
				delete this->m_ptr;
				delete this->m_count;
				this->m_ptr = NULL;
				this->m_count = NULL;
			}
		}
	}

	//拷貝構造函數
	MyShared_ptr(const MyShared_ptr& shared)
	{
		if (this != &shared)
		{
			this->m_ptr = shared.m_ptr;
			this->m_count = shared.m_count;
			(*this->m_count)++;
		}
	}

	//重載賦值操作符
	MyShared_ptr& operator=(const MyShared_ptr& shared)
	{
		if (this->m_ptr == shared.m_ptr)
		{
			return *this;
		}
		if (this->m_ptr)
		{
			if (*(--this->m_count) == 0)
			{
				delete this->m_ptr;
				delete this->m_count;
				this->m_ptr = NULL;
				this->m_count = NULL;
			}
		}
		this->m_ptr = shared.m_ptr;
		this->m_count = shared.m_count;
		(*this->m_count)++;
		return *this;
	}

    //重載->操作符
	T& operator->()
	{
		if (this->m_ptr)
		{
			return this->m_ptr;
		}
	}

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

    //實現 use_count函數
	size_t use_count()
	{
		return *this->m_count;
	}



private:
	T *m_ptr;  //內部指針,保證拷貝指向同一內存
	size_t *m_count;  //爲了保證指針的引用計數,這裏我是用了指針來做
};

 

測試的代碼我就放在一起了

//測試自己寫的智能指針和std提供的智能指針是否相同

//測試std提供的智能指針
void Std_SharedPtr_Test()
{
	shared_ptr<int>ptr(new int);
	shared_ptr<int>ptr2(ptr);
	shared_ptr<int> ptr3;
	ptr3 = ptr2;

	cout << "這是std::shared_ptr測試結果:" << endl;
	cout <<"ptr.use_count:"<<ptr.use_count() << endl;
	cout <<"ptr2.use_count:"<< ptr2.use_count() << endl;
	cout <<"ptr3.use_count:"<< ptr3.use_count() << endl;

    *ptr3 = 100;
	cout << "通過對*ptr3賦值 取ptr的值爲:"<<*ptr << endl;
	cout << endl;
}

//測試自己的智能指針
void MyShared_Ptr_Test()
{
	MyShared_ptr<int> ptr(new int);
	MyShared_ptr<int> ptr2(ptr);
	MyShared_ptr<int> ptr3;
	ptr3 = ptr2;

	cout << "這是MyShared_ptr測試結果:" << endl;
	cout << "ptr.use_count:" << ptr.use_count() << endl;
	cout << "ptr2.use_count:" << ptr2.use_count() << endl;
	cout << "ptr3.use_count:" << ptr3.use_count() << endl;

	*ptr3 = 200;
	cout << "通過對*ptr3賦值 取ptr的值爲:" << *ptr << endl;
}

int main()
{
	Std_SharedPtr_Test();
	MyShared_Ptr_Test();

	system("pause");
	return 0;
}

 

測試的結果

這是我自測結果,如有需要,自行測試。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章