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 delete is the memory going to leak or this delete is going to execute ?
相关问题
- Sorting 3 numbers without branching [closed]
- How to compile C++ code in GDB?
- Why does const allow implicit conversion of refere
- thread_local variables initialization
- What uses more memory in c++? An 2 ints or 2 funct
相关文章
- Class layout in C++: Why are members sometimes ord
- How to mock methods return object with deleted cop
- Which is the best way to multiply a large and spar
- C++ default constructor does not initialize pointe
- Selecting only the first few characters in a strin
- What exactly do pointers store? (C++)
- Converting glm::lookat matrix to quaternion and ba
- What is the correct way to declare and use a FILE
We also have to make sure that "exception" really means C++ exception which can be caught by try/catch. There are other exceptions as well in the system which C++ try/catch cannot catch (e.g. division by 0).
In such cases(beyond the scope of C++ Standards), also, "delete" will not be executed unless these exceptions are caught and the handler explicitly invokes "delete" appropriately.
It won't be called. Which is why you are encouraged to look at RAII. See Stroustrup
This depends on where that
delete
is. If it's inside thecatch
that catches the exception, it might invoke.If it's after the
catch
that catches the exception and thatcatch
doesn't return from the function (i.e. allows execution flow to proceed after thecatch
block) then thedelete
might be called.If the
delete
is not in acatch
block or after acatch
block that allows execution to proceed then thedelete
will not call.As you may imagine, in the two first cases above the
delete
will not be invoked if there is a throw before thedelete
:In the case you describe, memory is going to leak.
Two tricks to avoid this problem :
use smart pointers, which don't suffer from the same problem (preferred solution)
--> the smart pointer in constructed on the stack, its destructor is therefore called, no matter what, and deletion of the pointed content is provided in the destructor
use try/catch statements, and delete the item in catch statement as well