简体   繁体   English

C ++互斥和const正确性

[英]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 如果没有一个,如果这样的方法是const ,那么什么是不利/坏设计

Thank you 谢谢

You can mark data members with the keyword mutable to allow them to be modified in a constant member function, eg: 您可以使用关键字mutable标记数据成员,以允许在常量成员函数中修改它们,例如:

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. 尝试尽可能少地做这件事,因为滥用mutable是邪恶的。

I'm generally OK with mutable locks and caches for methods that are conceptually const . 对于概念上为const方法,我通常可以使用mutable锁和缓存。

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. 这严格来说是调用者不应该关注的实现细节,因此删除const指定等同于抽象中的小泄漏。

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 . 在某些平台上,通过句柄访问锁,因此您可以在方法上使用const而不必担心mutable

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM