Conversion or deletion of incomplete class pointer
You delete or cast to a pointer to an incomplete class
Description
This defect occurs when you delete or cast to a pointer to an incomplete class. An incomplete class is one whose definition is not visible at the point where the class is used.
For instance, the definition of class Body
is not visible when the
delete
operator is called on a pointer to
Body
:
class Handle { class Body *impl; public: ~Handle() { delete impl; } // ... };
Risk
When you delete a pointer to an incomplete class, it is not possible to call any nontrivial destructor that the class might have. If the destructor performs cleanup activities such as memory deallocation, these activities do not happen.
A similar problem happens, for instance, when you downcast to a pointer to an incomplete class (downcasting is casting from a pointer to a base class to a pointer to a derived class). At the point of downcasting, the relationship between the base and derived class is not known. In particular, if the derived class inherits from multiple classes, at the point of downcasting, this information is not available. The downcasting cannot make the necessary adjustments for multiple inheritance and the resulting pointer cannot be dereferenced.
A similar statement can be made for upcasting (casting from a pointer to derived class to a pointer to a base class).
Fix
When you delete or downcast to a pointer to a class, make sure that the class definition is visible.
Alternatively, you can perform one of these actions:
Instead of a regular pointer, use the
std::shared_ptr
type to point to the incomplete class.When downcasting, make sure that the result is valid. Write error-handling code for invalid results.
Examples
Result Information
Group: Object Oriented |
Language: C++ |
Default: On for handwritten code, off for generated code |
Command-Line Syntax:
INCOMPLETE_CLASS_PTR |
Impact: Medium |
Version History
Introduced in R2018b
See Also
Delete of void pointer
| MISRA C++:2008 Rule
5-2-4
| MISRA C++:2008 Rule
5-2-7
| MISRA C++:2008 Rule
5-2-8
| Find defects (-checkers)
Topics
- Interpret Bug Finder Results in Polyspace Desktop User Interface
- Interpret Bug Finder Results in Polyspace Access Web Interface (Polyspace Access)
- Address Results in Polyspace User Interface Through Bug Fixes or Justifications
- Address Results in Polyspace Access Through Bug Fixes or Justifications (Polyspace Access)