Search code examples
c++new-operator

Must new always be followed by delete?


I think we all understand the necessity of delete when reassigning a dynamically-allocated pointer in order to prevent memory leaks. However, I'm curious, to what extent does the C++ mandate the usage of delete? For example, take the following program

int main()
{
     int* arr = new int[5];
     return 0;
}

While for all intents and purposes no leak occurs here (since your program is ending and the OS will clean up all memory once it returns), but does the standard still require -- or recommend -- the usage of delete[] in this case? If not, would there be any other reason why you would delete[] here?


Solution

  • 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.