Is Object Releasing on Program Exit Really Needed?

后端 未结 4 466
天命终不由人
天命终不由人 2020-12-31 06:45

Is releasing objects on a programs exit/close needed?

In other words, let us say for the sake of argument, you have a button that closes your application, but right

相关标签:
4条回答
  • 2020-12-31 06:45

    Releasing can help you find bugs. More often than not dynamic memory problems trigger at release time (e.g., you attempt to release an invalid object). Always releasing can help you identify bugs that would otherwise be hard to find.

    0 讨论(0)
  • 2020-12-31 06:48

    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.

    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.

    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.

    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.

    0 讨论(0)
  • 2020-12-31 07:05

    On the iPhone, you don't need to, and as far as I am aware, you can't. After receiving applicationWillTerminate: you have a few seconds to save your state and then the OS kills your process. Build one of the sample apps and put a breakpoint in one of the dealloc methods. They never get hit.

    Here is a huge argument about it: link text

    Note: Objective C dealloc is not the same thing as a C++ Deconstructor. In a Deconstructor you can close files, handles, etc. In Objective C dealloc is just for releasing memory. You must close your other resources earlier since dealloc may never get called.

    0 讨论(0)
  • 2020-12-31 07:07

    Indeed it's not necessary, but if you may want to recycle someof your source and use it in another program, you might get memory leaks. Beside, never consider the OS to be without any fault. It could "forget" to free some resources.

    0 讨论(0)
提交回复
热议问题