C++ 为什么const共享\u ptr<;常数T>&;和const shared_ptr<;T>&;显示不同的引用计数?

C++ 为什么const共享\u ptr<;常数T>&;和const shared_ptr<;T>&;显示不同的引用计数?,c++,c++11,templates,shared-ptr,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>& 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;
}

请注意,
std::shared_ptr
std::shared_ptr
是不同的类型(即具有不同模板类型参数的类模板实例化是不同的类型)

当您将
ptr
(即a
std::shared_ptr
)传递到
f2
时,它不能绑定到直接引用
std::shared_ptr
;必须构造一个临时的
std::shared_ptr
,然后将其绑定到参数
ptr
。构建的
shared\u ptr
与原始
shared\u ptr
共享所有权,因此在
f2()
中使用计数增加到
2


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

,f2调用很可能必须构造一个隐式临时对象,作为从shared_ptr到shared_ptr转换的一部分,这就是执行f2时第二个refcount的来源。谢谢!有意义。根本不相关,简单地说:你应该的根本原因是C++在类模板参数上没有协方差。它改变了初始化为<代码> STD::SydDypPTR PTR(新FoO);<代码>并调用
f2(ptr)
。现在我可以看到refcount没有增加。非常感谢@阿鲁普拉顿罗伊:是的,对于这种情况,没有临时的麻烦。
main(): counts: 1
f1(): counts: 1
f2(): counts: 2
main(): counts: 1