How to free memory in try-catch blocks?

后端 未结 9 2131
时光说笑
时光说笑 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 19:01

    The general answer is use RAII.

    However, its possible to solve it by moving the variable out of the try{} scope:

    char * heap = NULL;
    try {
      heap = new char [50];
      ... stuff ...
    } catch (...) {
      if (heap) {
        delete[] heap;
        heap = NULL;
      }
      ... however you want to handle the exception: rethrow, return, etc ...
    }
    

    Please note that I'm not recommending this as a good practice - but more of a down & dirty to be used only if you really know the risks and are still willing to take them. Personally, I'd use RAII.

    Peace

提交回复
热议问题