Re: Writing exception-safe code

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 call)
{
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 call)
{
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

Would you like to post a relpy?


This post is a reply to:
Re: Writing exception-safe code
Dear mate Yes I got it.. So back to one of the things I love best ;-) look at source critically and try to improve it ;-) I saw the changes... So why not (more...)

Follow-ups:
Re: Writing exception-safe code
Dear Peter Actually out of memory will anyway terminate the program ( yes I am thinking about the **lazy memory allocation ** scheme use by many platforms ) ---------------------- man malloc --------------------------- By (more...)