Search code examples
c++constantsshared-ptr

Why does copying a const shared_ptr& not violate const-ness?


Even though my code compiles fine, this is something that has been bugging me, and I wasn't able to find an answer on stackoverflow. The following generic constructor is one way to pass a shared_ptr to a class instance in the constructor.

MyClass {
  MyClass(const std::shared_ptr<const T>& pt);
  std::shared_ptr<const T> pt_;  //EDITED: Removed & typo
};

MyClass::MyClass(const std::shared_ptr<const T>& pt)
  : pt_(pt)
{ }

This compiles fine. My question is the following: In my understanding, declaring a parameter const like this:

void myfunc(const T& t)

promises not to change t. However, by copying the shared_ptr pt to pt_, am I not effectively increasing the use count of the shared_ptr pt, thereby violating the supposed const-ness?

This might be a fundamental misunderstanding of shared_ptrs on my side?

(For anybody reading this looking to implement it, note that this might be a better implementation)


Solution

  • One of the members that std::shared_prt<> must have is the old fashioned copy constructor:

    shared_ptr(const shared_ptr& r) noexcept;
    

    The standard says (C++11 20.7.2.2.1/18 "shared_ptr constructors") that "if r is empty, constructs an empty shared_ptr object; otherwise, constructs a shared_ptr object that shares ownership with r".

    The standard doesn't make mention of how "shares ownership with r" might be accomplished though a const reference. Some options might be:

    • the private members that implement shared ownership semantics might be marked mutable
    • the data structures that implement shared ownership might not actually live in the shared_ptr object - they might be a separate set of objects that might be obtained through a pointer, for example.