Skip to content

scoped_lock constructor could be nodiscard like in libstdc++ #89388

@steakhal

Description

@steakhal

Consider this code:

#include <mutex>

int num;
std::mutex m;
void top() {
    if (std::scoped_lock{m}; num > 10) { // no-warning :(
        num = 1;
    }
    if (std::lock_guard{m}; num > 11) { // warn: nodiscard
        num = 2;
    }
}

The constructor of std::scoped_lock should have the [[nodiscard]] attribute to catch mistakes like the one in the example, creating a temporary scoped_lock object and leaving the access of the global variable unguarded.

If we use libstdc++, we get the following warning ignoring temporary created by a constructor declared with 'nodiscard' attribute [-Wunused-value]. Maybe we could also have this nodiscard attribute too.

Note that for instance lock_guard works as expected, and has the ``nodiscard` attribute.

Metadata

Metadata

Assignees

Labels

enhancementImproving things as opposed to bug fixing, e.g. new or missing featurelibc++libc++ C++ Standard Library. Not GNU libstdc++. Not libc++abi.

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions