Memory Free and Exceptions

I have a question regarding memory deallocation and exceptions. when I use delete to delete an object created on the heap. If an exception occurs before this deletion, is there a memory leak or will it be deleted?

+5
source share
4 answers

It depends on where it is delete. If inside catch, which catches an exception, it can cause.

try {
    f();  // throws
} catch( ... ) {
    delete p;  // will delete
}

If after catch, which catches the exception and that catchdoes not return from the function (i.e., allows execution of the execution thread after the block catch), then it can be called delete.

try {
    f();  // throws
} catch( ... ) {
    // execution proceeds beyond catch
}
delete p;  // will delete

delete catch catch, , delete .

try {
    f();  // throws
    delete p;  // will not delete
}  // ...

, delete , delete :

try {
    f();  // throws
} catch( ... ) {
    g();  // throws
    delete p;  // will not delete
}
+3

, , .

, :

  • , ( )
    - > , , ,

  • try/catch catch.

+5

. RAII. . Stroustrup

+2

, "" ++, try/catch. , ++ try/catch (, 0).

( ++-), , "delete" , , "" .

0

All Articles