Could someone please help me out why the output is 2 and not 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.
Note that y is a variable but not an object. 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.)
Maybe the following code illustrates the way in which y does not hold a share of the ownership:
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With