CppCoreGuidelines icon indicating copy to clipboard operation
CppCoreGuidelines copied to clipboard

Make mutexes mutable to preserve function constness

Open grahamreeds opened this issue 9 years ago • 3 comments

Something I have recently seen is people removing const from read only functions due to adding a mutex to control access and of course mutex changes state when used.

Example:

// rvo will use the vector move constructor...
std::vector<widget> get() const
{
    std::unique_lock<std::mutex> lk(cs_);
    std::vector<widget> copy(widgets_);
    return copy;
}

// in class definition
mutable std::mutex cs_;
std::vector<widget>widgets_;

grahamreeds avatar Jul 28 '16 06:07 grahamreeds

That's @hsutter 's "M&M rule" (mutable and mutex go together): https://herbsutter.com/2013/05/24/gotw-6a-const-correctness-part-1-3/

cubbimew avatar Aug 02 '16 14:08 cubbimew

Herb, we should consider a "use mutable when" rule. Sergey, could you please write up a rule about objects that are internally synchronized--mutex, atomic, lock-free queue--and submit it as a PR?

Bjarne suggests need two rules: application for synchronization and when you want a mutable.

AndrewPardoe avatar Apr 10 '17 18:04 AndrewPardoe

Is this still being considered for inclusion? @hsutter @AndrewPardoe @cubbimew ?

catskul avatar May 17 '21 18:05 catskul