【问题标题】:Why do const shared_ptr<const T>& and const shared_ptr<T>& show different reference counts?为什么 const shared_ptr<const T>& 和 const shared_ptr<T>& 显示不同的引用计数?
【发布时间】:2017-10-22 19:00:22
【问题描述】:

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

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

【问题讨论】:

  • 很可能 f2 调用必须构造一个隐式临时对象作为从 shared_ptr 转换为 shared_ptr 的一部分,这就是 f2 时第二个引用计数的来源执行。
  • 谢谢!有道理。
  • 完全不相关,仅供参考:您应该use make_shared instead of new
  • 根本原因是C++对类模板参数没有协方差

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


【解决方案1】:

请注意,std::shared_ptr&lt;Foo&gt; 和 std::shared_ptr&lt;const Foo&gt; 是不同的类型(即具有不同模板类型参数的类模板实例化是不同的类型)。

当你将ptr(即一个std::shared_ptr&lt;Foo&gt;)传递给f2时,它不能直接绑定到std::shared_ptr&lt;const Foo&gt;;必须构造一个临时的std::shared_ptr&lt;const Foo&gt;,然后绑定到参数ptr。构造的shared_ptr 与原始shared_ptr 共享所有权,因此f2() 中的use_count 增加到2。

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

【讨论】:

  • 我把初始化改成std::shared_ptr&lt;const Foo&gt; ptr( new Foo );,叫f2( ptr )。现在我可以看到引用计数没有增加。非常感谢!
  • @ArupRatonRoy 是的,在这种情况下,暂时没有麻烦。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-07-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-18
  • 1970-01-01
  • 2010-11-27
相关资源
最近更新 更多