栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

shared

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

shared

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实现

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/835874.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号