Lock guard constructed as an unnamed temporary

ID

c.correctness.temporary_raii_object

Severity

low

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Concurrency

Language

C / C++

Description

Reports a std::lock_guard, std::unique_lock, or std::scoped_lock constructed as an unnamed temporary rather than bound to a named variable.

Rationale

A temporary object is destroyed at the end of the full expression that created it — here, immediately after the semicolon that ends the statement, and before the very next line runs. The guard therefore releases the mutex right away, so every statement after it executes with no lock held at all, silently defeating the mutual exclusion the code appears to establish.

The following code illustrates the pattern detected by this rule:

std::mutex m;
int shared_state = 0;
void bumps_without_protection()
{
    // FLAGGED: Lock guard constructed as an unnamed temporary
    std::lock_guard<std::mutex>(m);
    shared_state++;
}

Remediation

Bind the guard to a named variable so it stays alive for the rest of the scope: std::lock_guard<std::mutex> guard(mutex);.

Configuration

This detector does not need any configuration.

© 2026 Xygeni. All rights reserved