简体   繁体   中英

Freeing a global variable in delphi

I am aware that it is not wise to use global variables indiscriminately. However, I needed to use one - a TStringList. My question is how (and where) do I free it? Searched, but could not find any documentation on it.

Thanks.

This can be answered by keeping in mind the basic principle of memory management: the Single Ownership Principle . Every variable should have one single owner whose responsibility it is to clean it up.

Whatever code creates your TStringList should also be responsible for destroying it (and, if it's a global, setting the global variable to nil ) at the appropriate time. So where are you creating it?

When I have globals, generally representing important resources, they're usually set up by an object that manages the entire program. They get created on initialization, and cleaned up during destruction of the main object. On the other hand, if you're creating it in an initialization section of a unit, you'll want the cleanup to be in that same unit's finalization section.

A TStringList should be safe to initialize in initialization and free in finalization sections.

As recommendation, consider encapsualting the access to the global variable into a function, this way you could move the var declaration into the implementation part and have more control over it.

Note that initialization and finalization may be inappropriate in other cases. Especially when threads are involved or LoadLibrary() / FreeLibrary() calls are required, it is better to have dedicated procedures to do that in the normal program flow. Both initialization and finalization sections are executed in a state, where Windows prevents certain things.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM