How to free memory in try-catch blocks?

后端 未结 9 2322
时光说笑
时光说笑 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:43

    OK mister Java programmer:

    try
    {
        // Exception safe dynamic allocation of a block of memory.
        std::vector  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?
    }
    

提交回复
热议问题