智能指针的使用和原理

本文介绍了智能指针shared_ptr的使用,包括make_shared、堆上资源指针构造、拷贝构造和赋值操作。通过示例展示了智能指针如何自动管理对象生命周期,特别是在循环引用时使用weak_ptr来解决。同时提到了unique_ptr的特性,它不允许拷贝和赋值,生命周期结束即自动销毁。最后强调了RAII原则在C++编程中的重要性。
摘要由CSDN通过智能技术生成

不多说一个Demo上来

void other(shared_ptr<vector<int>>& smart_p2)
{
	shared_ptr<vector<int>>smart_p4 = smart_p2;//赋值重载
	printf("1,2,3,4数组的引用计数是%d\n", smart_p2.use_count());
}
void testSharePtr()
{
	shared_ptr<vector<int>> smart_p1 = make_shared<vector<int>>(10, 9);//make_shared函数得到
	for (auto e : *smart_p1)
	{
		cout << e;
	}
	vector<int> * p2=new vector<int>(); 
	*p2 = { 1,2,3,4 };
	shared_ptr<vector<int>>smart_p2(p2);//使用指向堆上资源的指针构造
	shared_ptr<vector<int>>smart_p3(smart_p2);//拷贝构造
	other( smart_p2);
	smart_p2->push_back(5);
	printf("1,2,3,4数组的引用计数是%d\n", smart_p2.use_count());
	cout << "数组最后一个元素变成; " << *(smart_p3->end() - 1) <<endl;

	//如果2个shared_ptr指针循环调用,即A对象的指针指向B,B对象的指针指向A,则会循环引用,很好解决,把其中一个指针换成weak_ptr
}

构造方法在里面,

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值