I have a simple question hopefully - how does one free memory which was allocated in the try block when the exception occurs? Consider the following code:
try
{
The easiest way would be to declare the variable before the try block, and then just do the initialization within the block.
Either move the new before the try, so that the pointer is still in scope, or use a smart pointer like shared_ptr or unique_ptr (in a pinch, auto_ptr, but it has issues) that will clean up for you on exit. Exceptions are a huge reason why smart pointers are important.
Yes - if you are considering the simplicity - pointer that is outer to your try block is the solution.
Regards
OK mister Java programmer:
try
{
// Exception safe dynamic allocation of a block of memory.
std::vector<char> heap(50);
// DO STUFF
// Note in C++ we use stack based objects and their constructor/destructor
// TO give a deterministic cleanup, even in the presence of exceptions.
//
// Look up RAII (bad name for a fantastic concept).
}
catch (...)
{
cout << "Error, leaving function now";
return 1; // Though why you want to return when you have not fixed the exception is
// slightly strange. Did you want to rethrow?
}
Agreed with the answers on RAII and smart pointers.
However, if you insist, you can do this:
try { dangerous operations }
catch { cleanup; throw; }
I have to agree with all those that said RAII, however, I'd use Boost's shared_array instead of an auto_ptr. Auto pointer calls delete and not 'delete []' which will cause leaks with an array.