Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::shared_ptr use_count() value

Tags:

c++

c++11

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;
}
like image 389
bencemeszaros Avatar asked Jul 23 '26 18:07

bencemeszaros


1 Answers

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);
like image 137
Kerrek SB Avatar answered Jul 26 '26 08:07

Kerrek SB



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!