const member functions
If a member function does not change the object it belongs to, it should be marked as const. This does not only help the reader to easier understand the code, but also the compiler to optimize the binary. A const member function can be called on a const object. So far, so good. But what if you need to make such a method thread safe?
logical constness
Logical constness describes when it is Ok to make an object member mutable, and is thoroughly explained in the book Effective C++ by Scott Meyers. Contrary to bitwise constness, logical constness allows to modify some of the members of the object: the ones that are not important or meaningful to the logic of the class. Such members could be technical implementation details as e.g. mutexes, and we should be fine using the mutable keyword here:
class Foo {
void doSomething() const {
std::lock_guard<std::mutex> lock;
readFromStructure();
};
private:
mutable std::mutex mutex_;
};
bitwise constness
Bitwise const is when a method doesn’t and isn’t allowed to modify any of the non-static members of the object at all. This is C++’s default behavior, and one should consider carefully which member can be made mutable.