Aru*_*Roy 10 c++ templates shared-ptr c++11
对于以下代码段,它在方法中显示不同的引用计数.有人可以解释为什么这些价值不同吗?
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;
}
Run Code Online (Sandbox Code Playgroud)
相应的输出:
main(): counts: 1
f1(): counts: 1
f2(): counts: 2
main(): counts: 1
Run Code Online (Sandbox Code Playgroud)
son*_*yao 11
需要注意的是std::shared_ptr<Foo>与std::shared_ptr<const Foo>不同类型的(即使用不同的模板类型参数的类模板实例是不同的类型).
当你传递ptr(即a std::shared_ptr<Foo>)时f2,它不能被std::shared_ptr<const Foo>直接引用; std::shared_ptr<const Foo>必须构造临时,然后绑定到参数ptr.构建的shared_ptr股份所有权与原来的shared_ptr,所以use_count增加到2在f2().
临时将在f2( ptr );结束时销毁; 然后use_count减少到1.