This is a draft version of a MISRA C++ 202x rule proposed for public review.
MISRA Rule 9.2.1
Category: Required
Analysis Type: Decidable, Single Translation Unit
Amplification
This rule only applies to explicit type conversions that use functional notation.
Rationale
An explicit type conversion that uses functional notation is composed of a type name followed by parentheses or braces. It
creates a temporary object that is discarded at the end of the statement. This notation can appear to be very similar to the declaration of a
variable, except that it does not contain a variable name.
If the intent was to declare a variable for scope-based resource management (e.g. std::lock_guard
), the destruction side effects which
were expected to occur at the end of the containing block will instead occur immediately (e.g. the lock is prematurely released).
Example
In the following example, the redundant parentheses surrounding b_mutex
violate MISRA C++ 2023 Rule 6.0.1 (Block scope
declarations shall not be visually ambiguous).
void f1()
{
std::unique_lock< std::mutex > a_mutex; // Declaration, rule does not apply
std::unique_lock< std::mutex > ( b_mutex ); // Declaration, rule does not apply
}
void f2()
{
std::scoped_lock { a_mutex }; // Non-compliant
// - locks and unlocks here
// Unprotected
}
void f3()
{
std::scoped_lock ( a_mutex, other_mutex ); // Non-compliant
// - locks and unlocks here
// Unprotected
}
void f4()
{
f( std::unique_lock { a_mutex } ); // Compliant - type conversion is
// not an expression statement
}
Copyright The MISRA Consortium Limited © 2023