Search code examples
c++shared-ptr

shared_ptr and use_count


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?


Solution

  • 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.