Search code examples
c++memoryraiimemory-management

Why are destructors necessary in C++?


Why must we use destructors to de-allocate memory in c++,

As we can use

delete or delete[]   

Is it not true that all the memory used up by a program is released when the program terminates.


Solution

  • "we use destructors to de-allocate memory"

    What you are actually writing about are deallocation functions operator delete and operator delete[].

    "Is it not true that all the memory used up by a program is released when the program terminates?"

    AFAIK this is OS specific, yet the point is not what happens after the program terminates. The point is about what happens during the execution. There are many applications that run for several hours or even weeks and memory leaks might have very unpleasant consequences in these (not that memory leaks wouldn't be unpleasant in terms of other programs).

    When you program reaches the point, where the resources that you've allocated are not needed anymore, you should do your very best to free them using appropriate means. And once your program terminates: Relying on OS cleaning your mess doesn't seem to be much of a good practice ;)