MISRA C++:2023 Rule 18.3.3
Handlers for a function-try-block of a constructor or destructor shall not refer to non-static members from their class or its bases
Since R2024b
Description
Rule Definition
Handlers for a function-try-block of a constructor or destructor shall not refer to non-static members from their class or its bases. 1
Rationale
The handler catch blocks of a function try block
handle exception that are raised from the body of the function and the initializer list.
When used in class constructors and destructors, these catch blocks might
handle exceptions that arise during the creation or destruction of the class nonstatic
members. That is, the catch blocks might be executed before or after the
lifetime of the nonstatic members of a class. If the nonstatic members of a class are
accessed in such catch blocks, the compiler might attempt to access
objects that are not created yet or already deleted, which is undefined behavior. For
instance:
class C{
private:
int* inptr_x;
public:
C() try: inptr_x(new int){}
catch(...){
intptr_x = nullptr;
//...
}
};C is implemented by using a function
try block to handle any exception arising from the memory allocation
operation in the initializer list. In the catch block of this
function-try block, the class member C.intptr_x is
accessed. The catch block executes when the memory allocation for
intptr_x failed. That is, the catch block attempts to access the member
before its lifetime, which is undefined behavior.To avoid undefined behavior, avoid using the nonstatic data members or base classes of an object in the catch block of the function-try-block implementation of its constructors and destructor.
Polyspace Implementation
If a statement in the catch block of a constructor or destructor
function-try block accesses any of these, Polyspace® flags the statement:
The nonstatic members of the object
The base classes of the object
The nonstatic members of the base classes
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
Check Information
| Group: Exception Handling |
| Category: Required |
Version History
Introduced in R2024b
1 All MISRA coding rules and directives are © Copyright The MISRA Consortium Limited 2021.
The MISRA coding standards referenced in the Polyspace Bug Finder™ documentation are from the following MISRA standards:
MISRA C:2004
MISRA C:2012
MISRA C:2023
MISRA C++:2008
MISRA C++:2023
MISRA and MISRA C are registered trademarks of The MISRA Consortium Limited 2021.