shared_ptr 和 use_count [英] shared_ptr and use_count
问题描述
在以下代码片段中:
shared_ptrp;{p = shared_ptr(new int);cout<<p.use_count()<<endl;}cout<<p.use_count()<<endl;
输出结果为
<前>11我不明白为什么第一个输出是 1
-- 不应该是 2
吗?
临时对象的生命周期不够长,第一个 p.use_count()
返回 2.临时对象被销毁首先,放弃对其拥有的任何事物的所有权.
此外,由于临时值是一个右值,对 p
的赋值将导致移动赋值,这意味着无论如何使用计数永远不会是 2(假设一个质量实现).所有权只是从临时转移到 p
,永远不会超过 1.
In the following code snippet:
shared_ptr<int> p;
{
p = shared_ptr<int>(new int);
cout<<p.use_count()<<endl;
}
cout<<p.use_count()<<endl;
The output comes out to be
1 1
I don't understand why the 1st output is 1
-- shouldn't it be 2
?
The temporary object's lifetime does not last long enough for the first p.use_count()
to return 2. The temporary object is destroyed first, relinquishing its ownership on anything it owned.
Furthermore, since the temporary is an rvalue, the assignment to p
will result in a move-assignment, which means the use-count will never be 2 anyway (assuming a quality implementation). Ownership is simply transferred from the temporary to p
, never exceeding 1.
这篇关于shared_ptr 和 use_count的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!