开发者

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 disadva开发者_如何学Cntage/bad design if such method is const

Thank you


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜