Must new always be followed by delete?
There is nothing that requires a delete[]
in the standard - However, I would say it is a very good guideline to follow.
However, it is better practice to use a delete
or delete[]
with every new
or new[]
operation, even if the memory will be cleaned up by the program termination.
Many custom objects will have a destructor that does other logic than just cleaning up the memory. Using delete
guarantees the destruction in these cases.
Also, if you ever move around your routines, you are less likely to cause memory leaks in other places in your code.
Dupe of Is there a reason to call delete in C++ when a program is exiting anyway?
Answer is that because of destructors that need to be run, it is sometimes necessary to delete the object before exiting the program. Also, many memory leak detection tools will complain if you don't do this, so to make it easier to find real memory leaks, you should try and delete all of your objects before exiting.
Please see:
When to use "new" and when not to, in C++?
About constructors/destructors and new/delete operators in C++ for custom objects
delete and delete [] the same in Visual C++?
Why is there a special new and delete for arrays?
How to track memory allocations in C++ (especially new/delete)
Array of structs and new / delete
What is the difference between new/delete and malloc/free?