From 6d912e8b51886ec1a94378764c89b11fdf8bcbf8 Mon Sep 17 00:00:00 2001 From: Jonathan Wakely Date: Thu, 26 Jan 2023 16:29:02 +0000 Subject: [PATCH] CP.44 improve example and add more accurate discussion (#2028) --- CppCoreGuidelines.md | 21 ++++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-) diff --git a/CppCoreGuidelines.md b/CppCoreGuidelines.md index 5925372..230a297 100644 --- a/CppCoreGuidelines.md +++ b/CppCoreGuidelines.md @@ -15184,15 +15184,26 @@ Flag "naked" `lock()` and `unlock()`. ##### Reason -An unnamed local objects is a temporary that immediately goes out of scope. +An unnamed local object is a temporary that immediately goes out of scope. ##### Example - unique_lock(m1); - lock_guard {m2}; - lock(m1, m2); + // global mutexes + mutex m1; + mutex m2; -This looks innocent enough, but it isn't. + void f() + { + unique_lock(m1); // (A) + lock_guard {m2}; // (B) + // do work in critical section ... + } + +This looks innocent enough, but it isn't. At (A), `m1` is a default-constructed +local `unique_lock`, which shadows the global `::m1` (and does not lock it). +At (B) an unnamed temporary `lock_guard` is constructed and locks `::m2`, +but immediately goes out of scope and unlocks `::m2` again. +For the rest of the function `f()` neither mutex is locked. ##### Enforcement