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.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With