Error handling
E.13
Never throw while being the direct owner of an object
Reason
That would be a leak.
Example
void leak(int x) // don't: might leak
{
auto p = new int{7};
if (x < 0) throw Get_me_out_of_here{}; // might leak *p
// ...
delete p; // we might never get here
}
One way of avoiding such problems is to use resource handles consistently:
void no_leak(int x)
{
auto p = make_unique<int>(7);
if (x < 0) throw Get_me_out_of_here{}; // will delete *p if necessary
// ...
// no need for delete p
}
Another solution (often better) would be to use a local variable to eliminate explicit use of pointers:
void no_leak_simplified(int x)
{
vector<int> v(7);
// ...
}
Note
If you have a local "thing" that requires cleanup, but is not represented by an object with a destructor, such cleanup must also be done before a throw. Sometimes, finally() can make such unsystematic cleanup a bit more manageable.