tags:

views:

109

answers:

2

hello.

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

+8  A: 

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.

snk_kid
thank you. I guess the question is really about design rather than how to implement
aaa
aaa@ marking mutex data members as mutable is one of the times it's kind of acceptable use case because it doesn't represent the object's real state.
snk_kid
In our product, this keyword is used three times and one of the three is exactly `mutable boost::mutex`. Some day I'll figure out how to get rid of the other two.
Cubbi
thanks, that was my impression as well, but I was not sure if it's sound design
aaa
@aaa in our code base we also use mutable for mutex data members, another acceptable use-case would be reference counted objects I mean the actual reference count member. Another sort of acceptable use-case is lazily evaluated objects with "is_dirty" flags.
snk_kid
+4  A: 

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 them method without worrying about mutable.

Adrian McCarthy