Rule A15-1-2 (required, implementation, automated)
An exception object shall not be a pointer.
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 289436 2017-10-04 10:45:23Z michal.szczepankiewicz $
#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 [7]: 15-0-2 An exception object should not have pointer type. C++ Core Guidelines [11]: E.13: Never throw while being the direct owner of an object