智能指针shared_ptr的引用计数,详见代码及说明
// shared_ptr的几种初始化方式
shared_ptr<int> p1; // null
shared_ptr<string> p2 = make_shared<string>(); // 非null, 调用string默认构造函数
if(p2 && p2->empty()) {
*p2 = "hello world";
}
shared_ptr<string> p4 = make_shared<string>("hello world"); // 非null
// shared_ptr引用计数调试
shared_ptr<int> p3 = make_shared<int>(100); // 非null,值初始化对象int(100)
int p3count = p3.use_count(); // 1,初始化,引用计数为1
shared_ptr<int> p5 = p3;
p3count = p3.use_count(); // 2,被拷贝,引用计数+1
int p5count = p5.use_count(); // 2,请思考
shared_ptr<int> p6(p3);
p3count = p3.use_count(); // 3,被拷贝,引用计数+1
p5count = p5.use_count(); // 3,请思考
int p6count = p6.use_count(); // 3,请思考
p5 = make_shared<int>(10);
p3count = p3.use_count(); // 2,请思考
p5count = p5.use_count(); // 1,被赋予新的shared_ptr,引用计数为1
p6count = p6.use_count(); // 2,请思考
p6 = make_shared<int>(20);
p3count = p3.use_count(); // 1,请注意
p5count = p5.use_count(); // 1,请注意
p6count = p6.use_count(); // 1,被赋予新的shared_ptr,引用计数为1
p3 = make_shared<int>(30); // 此时,引用计数递减为0,对象int(100)被释放
p3count = p3.use_count(); // 1,请注意
p5count = p5.use_count(); // 1,请注意
p6count = p6.use_count(); // 1,被赋予新的shared_ptr,引用计数为1
C++ primer 中文版 (第五版) 12章