c++ 智能指针笔记2 shared_ptr的循环引用和删除器 weak_ptr

1、shared_ptr

 shared_ptr和uinque_ptr的最大区别是,shared_ptr可以拷贝构造和赋值,而又为了避免多个智能指针管理一个普通指针,造成多起delete的问题,shared_ptr会维护一个引用计数,只有当这个计数等于0的时候才会真正的删除空间,其他的只是对引用计数的++和–。即
 1、如果引用计数是0,就说明自己是最后一个使用该资源的对象,必须释放该资源;
 2、 如果不是0,就说明除了自己还有其他对象在使用该份资源,不能释放该资源,否则其他对象就成野指针了。

void main()
{
	int *p = new int(10);
	int *q = new int(20);
	shared_ptr<int> sp(p);
	cout << *sp << endl;//10
	cout << "sp use  count = " << sp.use_count() << endl; //1
	sp.reset(q);
	cout << *sp << endl; //20
	cout << "sp use  count = " << sp.use_count() << endl;//1
	shared_ptr<int> sp1 = sp;
	cout << "sp use  count = " << sp.use_count() << endl;//2
	cout << sp.unique() << endl;//是否被唯一引用 不是 输出0
}

1.1 shared_ptr模拟

分析:需要维护一个指向堆上地址的指针,一个指向引用计数的指针,同时,为了实现多线程安全,也要加锁,维护一个指向mutex锁的指针。这里我们都需要的是指针,这是因为如果是指针的话只需要开辟一块空间,然后用指针指向,而如果不用指针,则每个 shared_ptr创建一个引用计数,就不具备原子性,也不是临界资源。

#include<iostream>
#include<string>
#include<memory>
#include<thread>
#include<mutex>
using namespace std;
template <class T>
class SharedPtr
{
public:
	SharedPtr(T* ptr = nullptr) : _ptr(ptr), _pRefCount(new int(1)), _pMutex(new mutex)
	{}
	SharedPtr(const SharedPtr<T>& sp) : _ptr(sp._ptr), _pRefCount(sp._pRefCount), _pMutex(sp._pMutex)
	{
		AddRefCount();
	}
	SharedPtr<T>& operator=(const SharedPtr<T>& sp)
	{
		if (_ptr != sp._ptr)
		{
			Release();
			_ptr = sp._ptr;
			_pRefCount = sp._pRefCount;
			AddRefCount();
		}
		return *this;
	}
	~SharedPtr()
	{
		Release();
	}
public:
	void AddRefCount()
	{
		_pMutex->lock();
		++(*_pRefCount);
		_pMutex->unlock();
	}
	void Release()
	{
		bool deleteflag = false;
		_pMutex->lock();
		if (--(*_pRefCount) == 0)
		{
			delete _ptr;
			delete _pRefCount;
			deleteflag = true;
		}
		_pMutex->unlock();
		if (deleteflag)
			delete _pMutex;
	}
	T& operator*()
	{
		return *_ptr;
	}
	T* operator->()
	{
		return _ptr;
	}
	int UseCount()
	{
		return *_pRefCount;
	}
	T* Get()
	{
		return _ptr;
	}
private:
	int* _pRefCount; // 引用计数
	T*   _ptr;       // 指向管理资源的指针
	mutex *_pMutex;
};

class Date
{
public:
	Date() { cout << "Date()" << endl; }
	~Date() { cout << "~Date()" << endl; }
	int _year = 0;
	int _month = 0;
	int _day = 0;
};

mutex mt;
void SharePtrFunc(SharedPtr<Date>& sp, size_t n)
{
	SharedPtr<Date> copy(sp);
	cout << sp.Get() << endl;
	for (size_t i = 0; i < n; ++i)
	{
		// 这里智能指针拷贝会++计数,智能指针析构会--计数,这里是线程安全的。
		//SharedPtr<Date> copy(sp);
		// 这里智能指针访问管理的资源,不是线程安全的。所以我们看看这些值两个线程++了3n次,但
		//是最终看到的结果,并一定是加了2n
		mt.lock();   //把异步进行顺序-->同步机制
		copy->_year++;
		copy->_month++;
		copy->_day++;
		mt.unlock();
	}
}

int main()
{
	SharedPtr<Date> p(new Date);
	cout << p.Get() << endl;
	const size_t n = 10000;
	thread t1(SharePtrFunc, p, n);   //t1
	thread t2(SharePtrFunc, p, n);   //t2
	thread t3(SharePtrFunc, p, n);   //t3
	t1.join();
	t2.join();
	t3.join();
	cout << p->_year << endl;
	cout << p->_month << endl;
	cout << p->_day << endl;
	return 0;
}

2、weak_ptr

 weak_ptr 常常是为了辅助shared_ptr来使用的 ,他不会增加shared_ptr的引用计数,实际上weak_ptr有一个自身的计数,所以当多次使用weak_ptr时,wp.use_count()会增加,但shared_ptr的引用计数不变。

void main()
{
	shared_ptr<int> sp(new int(10));
	shared_ptr<int> sp1 = sp;
	cout << "use count = " << sp.use_count() << endl;//2
	//弱指针
	weak_ptr<int> wp = sp;
	cout << "use count = " << sp.use_count() << endl;//2
	weak_ptr<int> wp1 = wp;
	cout << "weak use_count = " << wp.use_count() << endl;  //2
	if (!wp.expired())  //不为0 
	{
		shared_ptr<int> sp3 = wp.lock();  //从weak_ptr转化为shared_ptr,shared_ptr引用计数+1
		cout << "use count = " << sp.use_count() << endl;//3
	}
	cout << "use count = " << sp.use_count() << endl;//2
}

3、 循环引用

  循环引用常常是shared_ptr和 weak_ptr使用不当导致的。

struct ListNode
{
	int _data;
	shared_ptr<ListNode> _prev;
	shared_ptr<ListNode> _next;
	~ListNode()
	{
		cout << "~ListNode()" << endl;
	}
};
void main()
{
	shared_ptr<ListNode> node1(new ListNode);
	shared_ptr<ListNode> node2(new ListNode);
	cout << node1.use_count() << endl;  //1
	cout << node2.use_count() << endl;   //1
	node1->_next = node2;  //循环引用导致节点不能释放
	node2->_prev = node1;  //避免循环引用 智能指针
	cout << node1.use_count() << endl;  //2
	cout << node2.use_count() << endl;  //2
}

  输出的时候不能调用ListNode的析构函数,这是因为node1和node2存在循环引用的问题,node1->_next = node2; 则node2的引用计数+1,node2->_prev = node1; 则node1的引用计数+1,接下俩,在析构的时候,如果要析构node1,则必须先node1的引用计数变为1,而由于node2->_prev 指向的node1,所以要想node1的引用计数变为1,则必须先析构node2。
  而反过来,要想析构node2,又由于node1->_next = node2;,所以必须析构node1,这要就没有一个先后顺序,所以会循环引用,谁都没有被析构。
  改进办法是将 shared_ptr变为weak_ptr

struct ListNode
{
	int _data;
	weak_ptr<ListNode> _prev;
	weak_ptr<ListNode> _next;
	~ListNode()
	{
		cout << "~ListNode()" << endl;
	}
};
void main()
{
	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;
}

4、 shared_ptr删除器

  和我们上篇博客讲到的unique_ptr一样,可以有删除器,也是支持删除数组的。删除器其实就是写一个仿函数,其实也可以是函数或lamda表达式。

template<class T>
struct FreeFunc
{
	void operator()(T* ptr)
	{
		cout << "free:" << ptr << endl;
		free(ptr);
	}
};
template<class T>
struct DeleteArrayFunc
{
	void operator()(T* ptr)
	{
		cout << "delete[]" << ptr << endl;
		delete[] ptr;
	}
};
//一般可以采用仿函数的都可以使用仿函数对象
void main()
{
	FreeFunc<int> freeFunc;
	int *p = (int *)malloc(4);
	cout << "p = " << p << endl;
	shared_ptr<int> sp1(p, freeFunc);  //delete 仿函数对象
	shared_ptr<int> sp11((int *)malloc(4), FreeFunc<int>());  //delete 仿函数
	DeleteArrayFunc<int> deleteArrayFunc;
	shared_ptr<int> sp2((int*)malloc(4), deleteArrayFunc);//仿函数对象
	shared_ptr<int> sp22((int*)malloc(4), DeleteArrayFunc<int>());//仿函数
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值