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)
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:
mutable
shared_ptr
object - they might be a separate set of objects that might be obtained through a pointer, for example.