C++智能指针

本文详细介绍了C++中的三种智能指针:shared_ptr、weak_ptr和unique_ptr。shared_ptr通过get、use_count和swap等函数管理对象,可以使用make_shared创建;weak_ptr不增加引用计数,用于解决循环引用问题,需要通过lock获取shared_ptr访问数据;unique_ptr则独占资源,禁止拷贝,通过reset和release转移所有权。
摘要由CSDN通过智能技术生成

shared_ptr

1.get()函数:返回数据类型指针的引用

2.use_count()函数:返回管理对象的指针数

3.swap()函数:交换管理对象

4.reset()函数:重置管理对象

5.make_shared<>()函数:构建shared对象

#include <iostream>
#include <memory>
using namespace std;
class custom
{
public:
	void print()
	{
		cout << "成员函数" << endl;
	}
	~custom()
	{
		cout << "析构函数" << endl;
	}
};
int main()
{
	shared_ptr<int> pint(new int(11));//初始化
	cout << *pint << endl;//访问
	int* pInt = pint.get();
	cout << pint.use_count() << endl;//1
	shared_ptr<int> pint1(pint);
	cout << pint.use_count() << endl;//2
	shared_ptr<int> a(new int(12));
	shared_ptr<int> b(new int(21));
	a.swap(b);//a:21    b:12
	b.reset(new int(11));//b:11
    shared_ptr<int> ppint=make_shared<int>(1);
	{
		//自定义
		shared_ptr<custom> pcus(new custom);
		pcus->print();
		//自带删除器写法
		shared_ptr<custom> p(new custom[3], [](custom* temp){delete[] temp; });
	}
	return 0;
}

weak_ptr

1.不会累计use_count()计数

2.只能通过shared_ptr或者其他weak_ptr来构造

3.解决shared_ptr循环引用导致内存无法释放

4.不可使用*取值,只能用->

5.通过成员函数lock获取shared_ptr对象,然后再访问数据

#include <iostream>
#include <memory>
using namespace std;
class custom
{
public:
	custom() = default;
	void print()
	{
		cout << "调用成员函数" << endl;
	}
	~custom()
	{
		cout << "调用析构" << endl;
	}
};
int main()
{
	shared_ptr<custom> pcus(new custom);
	cout << pcus.use_count() << endl;//1
	weak_ptr<custom> pwcus(pcus);
	cout << pcus.use_count() << endl;//1
	pwcus.lock()->print();
	return 0;
}

unique_ptr

1.禁止拷贝赋值

2.操作管理对象时,只有一个有效

3.可以通过move函数转交所有权

4.reset函数结合release函数转交所有

#include <iostream>
#include <memory>
using namespace std;
class custom
{
public:
	custom() {}
	custom(int num):num(num){}
	int GetNum()
	{
		return num;
	}
	~custom()
	{
		cout << num << endl;
	}
protected:
	int num=0;
};
int main()
{
	unique_ptr<custom> punp(new custom(11));
	unique_ptr<custom> punp1;
	punp1 = move(punp);//move转交所有权
	unique_ptr<custom> punp2(move(punp1));
	punp.reset(new custom(1));//重置
	unique_ptr<custom> punp3;
	punp3.reset(punp2.release());//reset与release结合转交所有权
	{
		//带删除器
		unique_ptr<custom, void(*)(custom*)> punp4(new custom[3], [](custom* temp){ delete[] temp; });
	}
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值