...
Consider the situation in which A
is allocated and constructed first, and then B
is allocated and throws an exception. Wrapping the call to g()
in a try
/catch
block is insufficient because it would be impossible to free the memory allocated for A
. This noncompliant code example is a specific instance of EXP50-CPP. Do not depend on the order of evaluation for side effects.
Compliant Solution (std::unique_ptr
)
In this compliant solution, a std::unique_ptr
is used to manage the resources for the A
and B
objects with RAII. In the situation described by the noncompliant code example, B
throwing an exception would still result in the destruction and deallocation of the A
object when then std::unique_ptr<A>
was destroyed.
...
SEI CERT C Coding Standard | ERR33-C. Detect and handle standard library errors |
MITRE CWE | CWE 252, Unchecked Return Value |
...