Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do we use Finalization in Units?

Tags:

delphi

I would like to know WHY do we use "Finalization" if we want to destroy something when closing the application? doesn't closing the application frees all objects directly without calling .Free?

Thanks.

like image 985
user1512094 Avatar asked Aug 01 '12 09:08

user1512094


2 Answers

Doesn't closing the application frees all objects directly without calling Free?

No. Delphi class instances are not garbage collected and so they need to be manually destroyed.

However, if you are talking about an executable process, then it can be perfectly acceptable not to dispose of certain objects since the operating system will re-claim all resources owned by a process when that process terminates. So even though Delphi destructors don't run, the OS tidies everything up when a process terminates. It is not possible for a process to leak any system resources once it has terminated.

Note that if the unit is included in a DLL or a package then failure to destroy all objects at finalization time will lead to memory leaks, if that DLL is repeatedly loaded and unloaded into a single process.

If you know that your code only ever runs in an executable, then feel at liberty not to Free objects at finalization time. Be aware that if you are using a memory leak detection tool then doing so will result in your intentionally leaked object being treated as a memory leak. Deal with that by calling RegisterExpectedMemoryLeak.

One final point to make is that an object's destructor sometimes does more than free memory. Sometimes it can save values to a settings file, or the registry, for example. Naturally you would not want to omit running the destructor for such an object.

like image 103
David Heffernan Avatar answered Oct 24 '22 08:10

David Heffernan


Adding to the final point of David Hefferman's answer: There are other resources that might need to be freed correctly, like file handlers that generate a checksum or some hardware connected to the PC that must be put in a specific state (e.g. a laser to be turned off, which is what I am currently working with).

like image 5
dummzeuch Avatar answered Oct 24 '22 06:10

dummzeuch