C++实现一个线程安全版本的shared_ptr(以及如何设置删除器)

#include<iostream>
#include<mutex>
#include<thread>
using namespace std;

namespace LMJian {
	//设置删除器
	template<class T>
	class DFDef {
	public:
		void operator()(T*& _ptr) {
			delete _ptr;
			_ptr = nullptr;
		}
	};
	//线程安全版本的shared_ptr
	template<class T, class DF = DFDef<T>>
	class shared_ptr {
	public:
		shared_ptr(T* ptr = nullptr)
			:_ptr(ptr)
			, _ret(nullptr)
			, _mutex(nullptr)
		{
			if (_ptr) {
				_ret = new int(1);
				_mutex = new mutex;
			}
		}
		~shared_ptr() {
			Release();
		}
		shared_ptr(const shared_ptr<T>& ptr)
			:_ptr(ptr._ptr)
			, _ret(ptr._ret)
			, _mutex(ptr._mutex)
		{
			if (_ret)
				AddRef();
		}
		shared_ptr<T>& operator=(const shared_ptr<T>& ptr) {
			if (this != &ptr) {
				Release();

				_ptr = ptr._ptr;
				_ret = ptr._ret;
				_mutex = ptr._mutex;
				if (_ret) {
					AddRef();
				}
			}
			return *this;
		}
		T& operator *() {
			return *_ptr;
		}
		T* operator ->() {
			return _ptr;
		}
		int use_count()
		{
			return *_ret;
		}
	private:
		void Release() {
			if (_ptr && 0 == SubRef()) {
				DF()(_ptr);
				delete _ret;
				delete _mutex;
			}
		}
		void AddRef() {
			if (_ret)
			{
				_mutex->lock();
				++*_ret;
				_mutex->unlock();
			}
		}
		int SubRef() {
			if (_ret) {
				_mutex->lock();
				--*_ret;
				_mutex->unlock();
			}
			return *_ret;
		}
		T* _ptr;
		int* _ret;
		mutex* _mutex;
	};
}

struct ListNode
{
	int _data;
	//解决循环引用问题
	weak_ptr<ListNode> _prev;
	weak_ptr<ListNode> _next;
	~ListNode() { cout << "~ListNode()" << endl; }
};

void TestListNode()
{
	shared_ptr<ListNode> node1(new ListNode);
	shared_ptr<ListNode> node2(new ListNode);
	cout << node1.use_count() << endl;
	cout << node2.use_count() << endl;
	node1->_next = node2;
	node2->_prev = node1;
	cout << node1.use_count() << endl;
	cout << node2.use_count() << endl;
}
发布了161 篇原创文章 · 获赞 52 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/qq_42837885/article/details/103341109