The idea of RAII (resource initialization - initialization) is that the creation of an object and its initialization are combined into one inseparable action. This usually means that they are executed in the constructor of the objects.
Locked locks work by locking the mutex when they are constructed, and unlock it when they break. C ++ rules ensure that when a control flow leaves an area (even through an exception), objects local to the exit area are destroyed correctly. This means that instead of a local call to lock() and unlock() using a sliding lock, it is impossible not to accidentally unlock the mutex, for example. when an exception is thrown in the middle of the code between lock() and unlock() .
This principle applies to all resource acquisition scenarios to be released, and not just to locking mutexes. It is good practice to provide such “scope protection” classes for other operations with similar syntax.
For example, I recently worked on a data structure class that usually sends signals when it changes, but they must be disabled for some bulk operations. Providing an area protection class that disables them during construction and reenables them during destruction prevents potential unbalanced calls to the disconnect / enable functions.
Angew
source share