C++ 引用计数面小例子

C++ 引用计数面小例子

1. 初始代码

#include <iostream>
#include <map>
using namespace std;

class Parent {  };
class Son : public Parent
{
};

map<int, shared_ptr<Parent>> m1;


void add(int i, const shared_ptr<Parent>& spParent) {
	// 这里会由于 隐式类型转换造成一次引用计数
	m1[i] = spParent;
	// spParent引用计数是多少 --> 3
	// 这里由于类型转换会产生一个额外的引用,m1[i] = spParent存在一个引用,spSon也存在一个,所以是3
	cout << "spParent reference count:" << spParent.use_count() << endl;
}

int main(void)
{
	{
		shared_ptr<Son> spSon = make_shared<Son>();
		add(1, spSon);
		// spSon引用计数是多少 --> 2 
		// 因为m1[1]中有一个对象存活,且spSon也存活所以为2
		cout << "spSon reference count:" << spSon.use_count() << endl;
	}
	// m1中的智能指针对象引用计数是多少 --> 1 
	// 因为m1[1]中有一个对象存活,且spSon离开其作用与范围被销毁
	cout << "m1[1] reference count:" << m1[1].use_count() << endl;
	return 0;
}

上面代码的输出结果如下:

spParent reference count: 3
spSon reference count: 2
m1[1] reference count: 1

2. 优化

#include <iostream>
#include <map>
using namespace std;

class Parent {  };
class Son : public Parent
{
};

map<int, shared_ptr<Parent>> m1;
void add2(int i, const shared_ptr<Son>& spSon);

int main(void)
{
	{
		shared_ptr<Son> spSon = make_shared<Son>();
		// 优化后
		add2(1, spSon);
		// spSon引用计数是多少 --> 2
		cout << "spSon reference count:" << spSon.use_count() << endl;
	}
	// m1中的智能指针对象引用计数是多少 --> 1
	cout << "m1[1] reference count:" << m1[1].use_count() << endl;
	return 0;
}

// 如何优化
// 优化 -> 减少一次类型转换
void add2(int i, const shared_ptr<Son>& spSon) {
	m1[i] = spSon;
	// spSon引用计数是多少 --> 2
	cout << "spSon reference count:" << spSon.use_count() << endl;
}

优化后的输出如下:

spSon reference count: 2
spSon reference count: 2
m1[1] reference count: 1
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值