How to use std :: lock_guard without breaking const?

In the subclass, I have a private field std::mutex mthat I use in implementing the pure virtual method of the base class to return the value in a thread-safe way (the value can be updated by another thread):

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 tells me that this violates the correctness of const, creating an error:

error: binding 'const std :: mutex' to a link like 'Stand :: lock_guard :: mutex_type & {aka std :: mutex &}' discards classifiers

Is there a way to make this compatible and use it std::lock_guardwith const-correct? A simple change const std::lock_guarddoes not change anything. I really don’t understand which part is problematic, then again I am completely new to C ++ ...

+5
1

this const ( rvalue const SubClass *), , , const .

- const, const?:)

, , const, , . , const , .

, , -, const . , , :

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

Source: https://habr.com/ru/post/1691833/


All Articles