Dear all,
I’m now thinking a little bit about exception safety, though I have to admit not too much, and had the following experience. Initially I was tempted to write a function like this:
void ExpectedFunctionBase::addCall (auto_ptr
{
calls.push_back (call.release());
}
But… what’s the problem with the above code? Well, it’s not exception safe! call.release() would be called first - it will release the ownership and return the raw pointer in a temporary. Then push_back() would be called and if it fails to allocate memory for the new list element bad_alloc is thrown, thus leaking the raw pointer, which is now not owned by anybody. The solution would be to just split the above in two steps:
void ExpectedFunctionBase::addCall (auto_ptr
{
calls.push_back (call.get()); // allocate memory and store the pointer
call.release(); // release ownership - no leak if exception thrown above
}
I hope I didn’t miss anything ;-)
Regards,
Peter
