Explicit destructor call outside placement new
ID |
c.maintainability.explicit_destructor_call |
Severity |
low |
Remediation Complexity |
medium |
Remediation Risk |
high |
Remediation Effort |
medium |
Resource |
Resource Management |
Language |
C / C++ |
Description
This code calls the destructor explicitly. The compiler will still run it again when the object’s own storage duration ends, so the object is destroyed twice unless this call is paired with placement new into raw, un-owned storage. Double destruction is undefined behavior. If this really is placement new cleanup, keep the pairing obvious at the call site; otherwise remove the explicit call and let normal scope or delete handle destruction.
Rationale
This code calls the destructor explicitly. The compiler will still run it again when the object’s own storage duration ends, so the object is destroyed twice unless this call is paired with placement new into raw, un-owned storage. Double destruction is undefined behavior. If this really is placement new cleanup, keep the pairing obvious at the call site; otherwise remove the explicit call and let normal scope or delete handle destruction.
The following code illustrates the pattern detected by this rule:
struct Widget {
~Widget() {}
void foo();
};
void bug(Widget *p, Widget &r)
{
// FLAGGED: Explicit destructor call outside placement new
p->~Widget();
// FLAGGED: Explicit destructor call outside placement new
r.~Widget();
}