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