std::shared_ptr::operator-> constness

Hi

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:

void foo(const std::shared_ptr< MyHandler >& handler)
{
handler->callNonConstMethod();
}

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:

void foo(const std::shared_ptr< MyHandler >& handler)
{
std::shared_ptr< MyHandler > nonConstHandler(handler);
nonConstHandler ->callNonConstMethod();
}

Any thoughts on why the reference counter is mutable?
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.
Last edited on
void foo(const std::shared_ptr< const MyHandler >& handler)
void foo(const std::shared_ptr< MyHandler >& handler)

is equivalent to

void foo(MyHandler *const & handler)
Well, I know what const is, in all its context. Let me give you an example:

the std::basic_string provides the operator[] as follows:

reference operator[]( size_type pos );
const_reference operator[]( size_type pos ) const;

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.

1
2
3
4
void function_which_should_not_modify_object(std::shared_ptr<const MyHandler> handler)
{
    // can't modify the owned object here.
}

Last edited on
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

From http://en.cppreference.com/w/cpp/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
Last edited on
Topic archived. No new replies allowed.