How to free memory in try-catch blocks?

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

    The 'correct' answer is RAII and shared_ptr as mentioned above, but just to be complete: in your example, you could substitute

    char *heap = new char [50];
    

    with

    char *stack = static_cast( alloca(50) );
    

    alloca is almost identical to malloc, except that it alocs memory on the stack instead of the heap, so no matter how you function exits (throwing or now), the memory will be reclaimed, and no deletes or frees are necessary.

提交回复
热议问题