C++ mutex and const correctness

C++

C++ Problem Overview


Is there convention regarding whenever method which is essentially read-only, but has mutex/ lock which may need to be modified, is const or not?

if there is not one, what would be disadvantage/bad design if such method is const

Thank you

C++ Solutions


Solution 1 - C++

You can mark data members with the keyword mutable to allow them to be modified in a constant member function, e.g.:

struct foo 
{
    mutable mutex foo_mutex;
    // ....
    void bar() const
    {
        auto_locker lock(foo_mutex);
        // ...
    }
};

Try to do this as little as possible because abusing mutable is evil.

Solution 2 - C++

I'm generally OK with mutable locks and caches for methods that are conceptually const.

Especially in the case of caching the result of a calculation for performance. That's strictly an implementation detail that shouldn't be of concern to the callers, so removing the const designation would be tantamount to a small leak in the abstraction.

With locks, I'd ask myself if the lock is just a private implementation detail. If the lock is shared with other objects, then it's actually part of the interface.

On some platforms, locks are accessed through handles, so you can use const on the method without worrying about mutable.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAnycornView Question on Stackoverflow
Solution 1 - C++snk_kidView Answer on Stackoverflow
Solution 2 - C++Adrian McCarthyView Answer on Stackoverflow