C++ is it necessary to delete dynamically allocate

2019-05-08 06:18发布

When using dynamically allocated objects in C++ eg:

TGraph* A = new TGraph(...);

One should always delete these because otherwise the objects might still be in memory when control is handed back to the parent scope. While I can see why this is true for subscopes and subroutines of a program, does the same count for the main scope?

Am I obliged to delete objects that were dynamically built inside main()? The reason why this seems a bit redudant to me is that when main ends, the program also ends, so there is no need to worry about memory leaks.

7条回答
戒情不戒烟
2楼-- · 2019-05-08 07:08

IMO it is best to always call delete properly:

  • to make it an automatic habit, making it less likely to forget it when it is really needed
  • to cover cases when non-memory resources (sockets, file handles, ...) need to be freed - these aren't automatically freed by the OS
  • to cater for future refactoring when the code in question might be moved out of main scope
查看更多
登录 后发表回答