[英]std::shared_ptr use_count() value
Could someone please help me out why the output is 2 and not 3? 有人可以帮我解释为什么输出是2而不是3? Thank you.
谢谢。
int main()
{
std::shared_ptr<int> x(new int);
std::shared_ptr<int> const& y = x;
std::shared_ptr<int> z = y;
std::cout << x.use_count() << std::endl;
return 0;
}
You only have two shared pointers: x
and z
. 您只有两个共享指针:
x
和z
。
Note that y
is a variable but not an object. 请注意,
y
是变量,但不是对象。 Its type is a reference type, not an object type. 它的类型是引用类型,而不是对象类型。
(In C++, not every object is a variable, and not every variable is an object.) (在C ++中,并非每个对象都是变量,并非每个变量都是对象。)
Maybe the following code illustrates the way in which y
does not hold a share of the ownership: 也许下面的代码说明在路
y
不持有所有权的份额:
std::shared_ptr<int> x(new int());
std::shared_ptr<int> const& y = x;
assert(y.use_count() != 0);
x.reset();
assert(y.use_count() == 0);
This line: 这一行:
std::shared_ptr<int> const& y = x; //doesn't increase use_count()
Is declaring y
as just a reference to x
. 将
y
声明为x
的引用。 It is just like another name for the same object. 它就像是同一个对象的另一个名称。 There is no
std::shared_ptr
object being created to increment the reference count. 没有创建
std::shared_ptr
对象来增加引用计数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.