对于以下代码段,它会在方法中显示不同的引用计数。有人可以解释为什么这些值不同吗?
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
答案 0 :(得分:11)
请注意transformFn
和std::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 );
。