Main Content

MISRA C++:2023 Rule 9.2.1

An explicit type conversion shall not be an expression statement

Since R2024b

Description

Rule Definition

An explicit type conversion shall not be an expression statement.

Rationale

This rule only applies to explicit type conversions that use functional notation. Functional notation for explicit type conversion in C++ occurs when a type name is followed by parentheses or braces to create a temporary object. In this case, the object is discarded after the statement ends.

Unnamed objects in an expression are destroyed immediately after the expression is evaluated rather than at the end of the code block that contains the expression. This can result in destruction side effects happening at a different time than a developer expects. This can commonly occur with scope-based resource management objects.

Polyspace Implementation

Polyspace® reports this rule violation whenever a local object is created and not named.

Troubleshooting

If you expect a rule violation but Polyspace does not report it, see Diagnose Why Coding Standard Violations Do Not Appear as Expected.

Examples

expand all

#include <mutex>

std::mutex my_mutex;

void example1() {
  std::unique_lock<std::mutex>{my_mutex};         	// Noncompliant

  // ...
}

void example2() {
  std::unique_lock<std::mutex> my_lock{my_mutex}; 	// Compliant

  // ...
}

Because std::unique_lock creates a temporary object but does not store it in a named variable, the lock is destroyed and the mutex is unlocked immediately after it is created. This can result in developer confusion if the developer intended to release the lock later in the program. Assign std::unique_lock to a variable to fix the defect.

Check Information

Group: Statements
Category: Required

Version History

Introduced in R2024b