Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ mutex and const correctness

Tags:

c++

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

like image 546
Anycorn Avatar asked Jul 13 '10 17:07

Anycorn


2 Answers

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.

like image 78
snk_kid Avatar answered Nov 07 '22 05:11

snk_kid


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.

like image 35
Adrian McCarthy Avatar answered Nov 07 '22 05:11

Adrian McCarthy