Is there a reason to call delete in C++ when a program is exiting anyway?

It is important to explicitly call delete because you may have some code in the destructor that you want to execute. Like maybe writing some data to a log file. If you let the OS free your memory for you, your code in your destructor will not be executed.

Most operating systems will deallocate the memory when your program ends. But it is good practice to deallocate it yourself and like I said above the OS won't call your destructor.

As for calling delete in general, yes you always want to call delete, or else you will have a memory leak in your program, which will lead to new allocations failing.


Yes, it helps to eliminate false positives when you run your program through a memory leak detection tool.


Yes.

  • The standard doesn't guarantee that the OS will clean up the memory. You can expect this on the mainstream platforms, but why take the chance?
  • You minimise clutter reported by tools like valgrind if you don't deliberately leak memory.
  • If you get into this habit, who's to say that you won't one day accidentally apply this approach somewhere it matters?
  • You may need object destruction. Usually just assume that you do. It doesn't hurt you.

Think about your class A having to destruct.
If you don't call delete on a, that destructor won't get called. Usually, that won't really matter if the process ends anyway. But what if the destructor has to release e.g. objects in a database? Flush a cache to a logfile? Write a memory cache back to disk?

You see, it's not just "good practice" to delete objects, in some situations it is required.


Consider the case where the object to be deleted acquired an external resource which can't be freed safely by the OS. If you don't call delete on that object, you have a real leak.