I have some confusion about the shared_ptr copy constructor. Please consider the following 2 lines:
-
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.
-
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?
The phenomenon you’re experiencing is not special to the shared pointer. Here’s a typical primeval example:
It is true that
x.phas typeint * constinsidef, but it is not anint const * const! In other words, you cannot changex.p, but you can change*x.p.This is essentially what’s going on in the shared pointer copy constructor (where
*ptakes the role of the reference counter).