为什么const shared_ptr <const t =“”>&amp;和const shared_ptr <t>&amp;显示不同的参考计数?

时间:2017-05-23 01:29:48

标签: c++ c++11 templates shared-ptr

对于以下代码段,它会在方法中显示不同的引用计数。有人可以解释为什么这些值不同吗?

class Foo {
};

void f1( const std::shared_ptr<Foo>& ptr ) {
   std::cout << "f1(): counts: " << ptr.use_count() << std::endl;
}

void f2( const std::shared_ptr<const Foo>& ptr ) {
   std::cout << "f2(): counts: " << ptr.use_count() << std::endl;
}

int main() {
   std::shared_ptr<Foo> ptr( new Foo );
   std::cout << "main(): counts: " << ptr.use_count() << std::endl;

   f1( ptr );
   f2( ptr );

   std::cout << "main(): counts: " << ptr.use_count() << std::endl;

   return 0;
}

相应的输出:

main(): counts: 1
f1(): counts: 1
f2(): counts: 2
main(): counts: 1

1 个答案:

答案 0 :(得分:11)

请注意transformFnstd::shared_ptr<Foo>是不同的类型(即具有不同模板类型参数的类模板实例是不同的类型)。

当您将std::shared_ptr<const Foo>(即ptr)传递给std::shared_ptr<Foo>时,它无法直接引用f2;必须构造临时std::shared_ptr<const Foo>,然后绑定到参数std::shared_ptr<const Foo>。构建的ptr与原始shared_ptr共享所有权,因此shared_ptr中的use_count增加到2

f2()结束时,临时将被销毁;然后use_count减少到f2( ptr );