How does the control block of a shared pointer behave with const shared pointers

540 Views Asked by At
const std::shared_ptr<int> x (new int (2));
const std::shared_ptr<int> y (x);

copying a shared pointer makes changes to the control block where the 'const' shared pointers point to, does that not contradict the constness part?

3

There are 3 best solutions below

19
On

The control block is an implementation detail that users do not have access to and should not be concerned with. It is not a part of shared_ptr interface and cannot be observed.

It is the shared_ptr pointer what is const. Which means you cannot reassign it.

It behaves similar to a plain const pointer in this regard: it can be copied, but cannot be reassigned.

0
On

shared_ptr contains (generally speaking) two pointers. One to hold an object and second one to 'internal' data with refcount etc. If you make shared_ptr constant it means you cannot modify these pointers, but you can without a problem modify objects they point to.

If this is a contradicion? For me not, but for sure there are people which would say it is. Kind of philosophical question. :)

6
On

It can either have the control block member declared as mutable (unlikely, see Maxim's comment), or (more likely) it can have a non-const pointer pointing to the control block as a member. Changing values of the pointed-to control block in a const shared_ptr is allowed, just reassigning that pointer isn't when it's const.

To take a real world example from MSVC2015 (I know I know), shared_ptr has a member _Rep :

private:
    _Ty *_Ptr;
    _Ref_count_base *_Rep;

The shared_ptr can modify the use count through _Rep.