Search code examples
c++c++11shared-ptrcopy-constructor

Inside the copy constructor of shared_ptr


I have some confusion about the shared_ptr copy constructor. Please consider the following 2 lines:

  1. It is a "constant" reference to a shared_ptr object, that is passed to the copy constructor so that another shared_ptr object is initialized.

  2. The copy constructor is supposed to also increment a member data - "reference counter" - which is also shared among all shared_ptr objects, due to the fact that it is a reference/pointer to some integer telling each shared_ptr object how many of them are still alive.

But, if the copy constructor attempts to increment the reference counting member data, does it not "hit" the const-ness of the shared_ptr passed by reference? Or, does the copy constructor internally use the const_cast operator to temporarily remove the const-ness of the argument?


Solution

  • The phenomenon you're experiencing is not special to the shared pointer. Here's a typical primeval example:

    struct Foo
    {
        int * p;
        Foo() : p(new int(1)) { }
    };
    
    void f(Foo const & x)  // <-- const...?!?
    {
        *x.p = 12;         // ...but this is fine!
    }
    

    It is true that x.p has type int * const inside f, but it is not an int const * const! In other words, you cannot change x.p, but you can change *x.p.

    This is essentially what's going on in the shared pointer copy constructor (where *p takes the role of the reference counter).