isocpp / CppCoreGuidelines

The C++ Core Guidelines are a set of tried-and-true guidelines, rules, and best practices about coding in C++
http://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines
Other
42.56k stars 5.43k forks source link

Make mutexes mutable to preserve function constness #655

Open grahamreeds opened 8 years ago

grahamreeds commented 8 years ago

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_;
cubbimew commented 8 years ago

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/

AndrewPardoe commented 7 years ago

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.

catskul commented 3 years ago

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