How to free memory in try-catch blocks?

后端 未结 9 2123
时光说笑
时光说笑 2021-01-31 18:33

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
 {         


        
相关标签:
9条回答
  • 2021-01-31 18:37

    The easiest way would be to declare the variable before the try block, and then just do the initialization within the block.

    0 讨论(0)
  • 2021-01-31 18:38

    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.

    0 讨论(0)
  • 2021-01-31 18:39

    Yes - if you are considering the simplicity - pointer that is outer to your try block is the solution.

    Regards

    0 讨论(0)
  • 2021-01-31 18:43

    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?
    }
    
    0 讨论(0)
  • 2021-01-31 18:55

    Agreed with the answers on RAII and smart pointers.

    However, if you insist, you can do this:

    try { dangerous operations } 
    catch { cleanup; throw; }
    
    0 讨论(0)
  • 2021-01-31 18:57

    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.

    0 讨论(0)
提交回复
热议问题