Can anyone explain to me why std::shared_ptr operator*() const and operator->() const are returning non constan pointer / reference to the shared object. It is rely annoying to see code like:
Further on the same subject it seems to me that the reference counter is mutable. That means, even though operator->() const and operator*() const would return const pointer / reference, you could still be able to do the following:
const on the end of a function declaration tells us that the function makes no changes to non-mutable class members of the class object. It has nothing to do with returning a const object.
Obviously the constan method returns constant reference, the non-const method returns non-const refrence. Why do we not have something similar for the std::shared_ptr dereferencing operators?
Please do not give me a lesson about const, I know the syntas. I am looking for an conceptual answer here. Thanks in advance.
Why are you passing a reference to a shared_ptr? If the function doesn't need to share ownership, then it doesn't need to know what is owning the object. Pass a const reference instead.
If you need a function to share ownership, but want to make sure that function doesn't modify the owned object.. make the owned object const, not the pointer.
The foo() in the initial post is not calling any member functions of std::shared_ptr, it has no business using a smart pointer at all, and should be taking const MyHandler& as parameter
In larger context, the issue is in fact the motivation for std::experimental::propagate_const
std::experimental::propagate_const is a const-propagating wrapper for pointers and pointer-like objects. It treats the wrapped pointer as a pointer to const when accessed through a const access path