是对象释放程序退出真的需要吗? [英] Is Object Releasing on Program Exit Really Needed?

查看:103
本文介绍了是对象释放程序退出真的需要吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个技术问题。
这不是关于正确编码的问题。

I have a technical question. This is NOT a question about proper coding.

我的问题是TECHNICALLY是在程序退出/关闭需要释放对象?

My question is TECHNICALLY is releasing objects on a programs exit/close needed?

换句话说,让我们说为了参数,你有一个按钮,关闭你的应用程序,但在关闭之前显示一个图像,然后你关闭应用程序。

In other words, lets say for the sake of argument, you have a button that closes your application, but right before you close you display a image, and then you close the application.

您是否需要在关闭应用程序之前释放该图像视图?当程序退出时,内存会自动释放,或者如果你不释放内存,内存会以某种方式活动?

Do you TECHNICALLY need to release that image view before you close the application? Will the memory automatically be freed when the program exits, or if you don't release it will the memory stay somehow "active"?

我知道你应该发布它,我的问题是关于技术方面,以及在幕后发生了什么。

I understand that you "should" release it, my question is about the technical side of it, and what happens behind the scenes.

谢谢。

推荐答案

没有必要。但是,如果你使用 valgrind 或类似的工具,你很快就会发现,留下所有的内存,使你陷入虚假的警告。

It's not necessary. But if you're using valgrind or a similar tool, you'll soon discover that leaving all of your memory dangling swamps you with false warnings.

在Linux方面,堆是使用 sbrk 系统调用生成的。这样一来,整个处理器的内存空间就会增加一个大块(因此只需要一个 sbrk 来为很多 malloc s)。当进程消失时,内核会回收 sbrk 分配的所有内存。这就是为什么你是安全的。内核也将关闭由该进程打开的任何文件描述符。

On the Linux side of things, the heap is grown using the sbrk system call. This grows the overall processor memory space by a large block at a time (so only one sbrk is needed to provide enough space for many mallocs). When the process goes away, the kernel reclaims all of the memory allocated by sbrk. This is why you're safe. The kernel will also close any file descriptors opened by that one process.

有几个问题可以出现。如果你的进程在不合时宜 fork ,任何打开的文件描述符将被复制。我已经看到这个清单本身作为一个TCP连接神秘地悬挂在原来的进程死亡后,这是 。此外,还有其他资源只是没有处理范围,因此当进程死亡时,它们不会被回收。这包括共享内存段,临时文件,命名管道和UNIX套接字,以及可能还有其他一些IPC机制。

There are a few problems that can come up. If your process ever forks at an inopportune moment, any open file descriptors will be duplicated. I have seen this manifest itself as a TCP connection mysteriously hanging alive after the original process died, which is nasty. In addition, there are other resources that are just not process-scoped, so they won't be reclaimed when the process dies. This includes shared memory segments, temporary files, named pipes and UNIX sockets, and probably a slew of other IPC mechanisms.

总之,内存是好的。文件描述符通常很好。一些更深奥的IPC功能将被破坏,如果不清理。

In summary? Memory is fine. File descriptors are usually fine. Some of the more esoteric IPC features will be horribly broken if not cleaned up.

这篇关于是对象释放程序退出真的需要吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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