简体   繁体   English

如何在不违反const正确性的情况下使用std :: lock_guard?

[英]How to use a std::lock_guard without violating const correctness?

In a subclass, I have a private std::mutex m field that I use in an implementation of a base class pure virtual method to return a value in a thread-safe way (the value can be updated by another thread): 在子类中,我有一个私有的std::mutex m字段,我在基类纯虚方法的实现中使用它以线程安全的方式返回一个值(该值可以由另一个线程更新):

int SubClass::get() const // implements 'virtual int get() = 0 const' of the base class
{            
    std::lock_guard<std::mutex> lck(m); 
    return value;
}

The compiler is telling me that this violates const correctness by producing an error: 编译器通过产生错误告诉我这违反了const正确性:

error: binding 'const std::mutex' to reference of type 'std::lock_guard::mutex_type& {aka std::mutex&}' discards qualifiers 错误:将'const std :: mutex'绑定到类型'std :: lock_guard :: mutex_type&{aka std :: mutex&}'的引用将丢弃限定符

Is there a way to make this compliant and use std::lock_guard in a const-correct way? 有没有办法使这个兼容并以const正确的方式使用std::lock_guard Simply changing it to const std::lock_guard changes nothing. 只需将其更改为const std::lock_guard I don't really understand which part is problematic, then again I'm quite new to C++ ... 我真的不明白哪个部分有问题,然后我再次对C ++很新...

The this pointer is implicitly const (it's actually an rvalue of type const SubClass * ), so any member you are accessing are const implicitly. this指针隐式为const (它实际上是const SubClass *类型的右值),因此您访问的任何成员都是隐式的const

If you could modify member object in a const function, then what would be the point of const ? 如果你可以在const函数中修改成员对象,那么const何在? :) :)

The lock guard wants to modify the mutex, to lock and unlock it, but because it is const , it cannot, that is the problem. 锁定保护程序想要修改互斥锁,锁定和解锁它,但因为它是const ,它不能,这就是问题所在。 It doesn't matter if the lock guard is const or not, because that has nothing to do with the ability of the lock guard to modify the mutex or not. 锁定保护装置是否为const并不重要,因为这与锁定装置修改互斥锁的能力无关。

To effectively solve this problem, there is a keyword you can use to mark member objects that can be modified in const qualified functions. 为了有效地解决这个问题,可以使用一个关键字来标记可以在const限定函数中修改的成员对象。 Now obviously, you shouldn't abuse this feature and mark every object of your class with it: 显然,你不应该滥用这个功能并用它来标记你班级的每个对象:

class SubClass {
/*...*/
private:
    mutable std::mutex m;
  //^^^^^^^
/*...*/
}; 

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

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