C++ mutex and const correctness
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
Solution 1:
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:
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
.