AutosarC++17_03-A15.1.2ΒΆ

An exception object shall not be a pointer

Required inputs: IR

Rationale

If an exception object of pointer type is thrown and that pointer refers to a dynamically created object, then it may be unclear which function is responsible for destroying it, and when. This may lead to memory leak.

If an exception object of pointer type is thrown and that pointer refers to an automatic variable, it allows using a variable after its destruction, leading to undefined behavior.

This ambiguity does not exist if a copy of the object is thrown.

Example
//% $Id: A15-1-2.cpp 271715 2017-03-23 10:13:51Z piotr.tanski $
#include <cstdint>
class A {
// Implementation
};
void fn(std::int16_t i) {
A a1;
A &a2 = a1;
A *a3 = new A;

if (i < 10) {
throw a1; // Compliant - copyable object thrown
}

else if (i < 20) {
throw A(); // Compliant - copyable object thrown
}

else if (i < 30) {
throw a2; // Compliant - copyable object thrown
}

else if (i < 40) {
throw & a1; // Non-compliant - pointer type thrown
}

else if (i < 50) {
throw a3; // Non-compliant - pointer type thrown
}

else if (i < 60) {
throw(*a3); // Compliant - memory leak occurs, violates other rules
}

else {
throw new A; // Non-compliant - pointer type thrown
}
}
See Also
  • MISRA C++ 2008 [6]: 15-0-2 An exception object should not have pointer type.
  • C++ Core Guidelines [10]: E.13: Never throw while being the direct owner of an object

Possible Messages

Key

Text

Severity

Disabled

throwing_pointer

Exception object of pointer type

None

False

Options