shared

shared,第1张

shared_ptr是c++中的一种常用智能指针,它能够解决C++程序员未及时释放内存空间导致的内存泄露问题。shared_ptr的实现核心是改变其中的引用计数值,下面是我实现的一个简单的shared_ptr,其中主要包括拷贝构造函数、赋值运算符等。

#include 
using namespace std;
template 
class myshared_ptr
{
public:
	myshared_ptr(T*value) //:ptr(value), count(new int(1))
	{
		ptr = value;
		count = new int(1);
	}
	myshared_ptr(const myshared_ptr&m)
	{
		ptr = m.ptr;
		count = m.count;
		(*count)++;
	}
	myshared_ptr&operator=(const myshared_ptr&m)
	{
		if (this != &m)
		{
			ptr = m.ptr;
			count = m.count;
			(*count)++;
		}
		return *this;
	}
	T&operator->()
	{
		return this->ptr;
	}
	~myshared_ptr()
	{
		(*count)--;
		if (*(this->count) == 0)
		{
			delete ptr;
			delete count;
			//ptr = nullptr;
			//count = nullptr;
			cout << "释放内存空间" << endl;
		}
	}
public:
	T*ptr;
	int*count;
};
void testshared_ptr()
{
	myshared_ptr res(new int(2));
	cout << *(res.count) << endl;
	myshared_ptr res2(res);
	cout << *(res2.count) << endl;
	myshared_ptr res3 = res;
	cout << *(res.count)<

执行上面代码输出如下,可见我们通过赋值运算符、拷贝构造函数都会增加引用计数值。而通过析构函数会减少引用计数值,直到引用计数为0时,释放内存空间。

1
2
3
3
3
2
1
释放内存空间

参考博客:shared_ptr的简单实现_haitaobiyao的博客-CSDN博客_shared_ptr实现

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/737691.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-04-28
下一篇2022-04-28

发表评论

登录后才能评论

评论列表(0条)