【发布时间】: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_sharedinstead ofnew -
根本原因是C++对类模板参数没有协方差
标签: c++ c++11 templates shared-ptr