Search code examples
c++shared-ptrsmart-pointers

How does counter decrement of smart pointer work?


Below is a sample code for shared pointer. I define a shared pointer inside curly braces scope. sp1 is initialized by new A (counter = 1) and sp1 is assigned to sp2 (copy and/or assignment increase the counter by 1 so, counter = 2). I always thought destructor of the A is called when counter becomes 0. But in my case the smart pointer when is about to get out of scope ( via the curly brace ) the counter is two.

My question is : who changed the counter from 2 to 0?

#include <iostream>
#include <memory>

using namespace std;

class A{
public:
    ~A(){

        std::cout << "~A" <<  std::endl;
    }    
};
int main(){
    {
        shared_ptr<A> sp1 (new A); 
        shared_ptr<A> sp2 = sp1;

        std::cout << "sp1 count = " << sp1.use_count() << std::endl;
        std::cout << "sp2 count = " << sp2.use_count() << std::endl;
    }

return 0;
}

EDIT: Link to paper on smart pointer

output:


sp1 count = 2

sp2 count = 2

~A


Solution

  • When your code gets to the end of main, the destructor for both sp1 and sp2 runs, which decrements the counter to zero - that is a VERY important part of shared pointers, that the destructor reduces the reference count and thus, when "nothing" is left, the destructor of the actual shared object gets called.

    The destuctor of shared_ptr will have some logic like this:

     counter--;    // Should be atomic!
     if (counter == 0)
     {
        delete owned_thing;
     }