0
我知道shared_ptr
类会自动管理动态对象。引用到shared_pointer的引用计数
在这里,我有一个功能f
返回const shared_ptr<int>
到int 2
。
我有两个版本main
在一个地方不同。版本A将返回值f
保存为共享指针,而版本B保存为共享指针参考。
using namespace std;
const std::shared_ptr<int> f() {
const std::shared_ptr<int> ret = std::make_shared<int>(2);
return ret;
}
int main() {
const std::shared_ptr<int> p = f(); // A
// const std::shared_ptr<int> &p = f(); // B
cout << p.use_count() << *p << endl; // prints 1 2
return 0;
}
两个版本打印1 2
。我对版本A没问题,因为p
是最后的shared_ptr
指向int
,因此use_count
是1
。
问题:为什么use_count
等于1
版本B?最后现有的shared_ptr
在哪里?
“std :: shared_ptr”的引用计数适用于实例,而不适用于引用。 –
@πάνταῥεῖ谢谢。对于版本A,是否是实例'p'?对于版本B,这是现有的实例?它是'f()'的返回值吗?也许我没有完全理解引用,我认为引用是对象的别名。 – sam
临时生存期与const引用一起出现。 – Jarod42