C ++是否需要在主作用域结束时删除动态分配的对象? [英] C++ is it necessary to delete dynamically allocated objects at the end of the main scope?

查看:116
本文介绍了C ++是否需要在主作用域结束时删除动态分配的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当在C ++中使用动态分配的对象时,例如:

When using dynamically allocated objects in C++ eg:

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

这些都应始终 delete
控制被交还给父作用域时,对象可能仍然在内存中。虽然我可以看到为什么对于子程序和程序的子程序是这样, main scope?

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?

我必须在 main()中动态建立删除物件吗?这对我来说有点沮丧的原因是当 main 结束时,程序也结束了,所以没有必要担心内存泄漏。

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.

推荐答案

大多数现代操作系统总是回收他们分配给一个程序(进程)的所有内存。

OS doesn'

Most of the modern OS always reclaim back all memory they allocated to a program(process).
The OS doesn't really understand if your program leaked memory it merely takes back what it allocatted.

但是有更大的问题,而不是只是内存损失:

But there are bigger issues at hand than just the memory loss:

请注意,如果对象的析构函数 delete 需要被调用,执行一些不平凡的操作,你的程序依赖于副作用那么您的程序就会成为未定义行为 [Ref 1] 。一旦发生所有的赌注都关闭,你的程序可能会显示任何beahvior。

Note that if the destructor of the object whos delete needs to be called performs some non-trivial operation and your program depends on the side effects produced by it then your program falls prey to Undefined Behavior[Ref 1]. Once that happens all bets are off and your program may show any beahvior.

此外,操作系统通常会回收已分配的内存,但不会回收其他资源,因此您可能会间接泄露这些资源。这可能包括处理文件描述符的操作或程序本身的状态等。

Also, An OS usually reclaims the allocated memory but not the other resources, So you might leak those resources indirectly. This may include operations dealing with file descriptors or state of the program itself etc.

因此,一个好的做法是总是通过调用 delete delete []

Hence, it is a good practice to always deallocate all your allocations by calling delete or delete [] before exiting your program.

[参考文献1] C ++ 03 Standard 3.8 Para 4: / strong>

[Ref 1]C++03 Standard 3.8 Para 4:


如果没有显式调用析构函数, .5)不用于释放存储,析构函数不应被隐式调用,任何依赖于析构函数产生的边效应的程序都具有未定义的行为

这篇关于C ++是否需要在主作用域结束时删除动态分配的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆