Mike Schaeffer's Weblog
Tue, 12 Apr 2005
Global variables tend get a bad rap, kind of like goto and pointers.
Personally, I think they can be pretty useful if you are careful.
Here are the guidelines I use to determine if a global variable
is an appropriate solution:
reddit this! Digg Me!
- Will there ever be a need for more than one instance of the variable?
- How much complexity does passing the variable to all its accessors
entail?
- Does the variable represent global state? (A heap free list, configuration
information, a pool of threads, a global mutex, etc.)
- Can the data be more effectively modeled as a static variable in a
function or private member variable in a singleton object? (Both
of these are other forms of global storage, but they wrap the variable
accesses in accessor functions.)
- Can you support the lifecycle you need for the variable any other way? Global
variables exist for the duration of your program's run-time. Local variables
exist for the duration of a function. If you don't have heap allocated
variables, or if your heap allocator sucks, then a global variable might
be the best way to get to storage that lasts longer than any one function
invocation.
- Do you need to use environment features that are specific to globals?
In MSVC++, this can mean things like
specifying the segment in which a global is stored or declaring a variable as
thread-local.
reddit this! Digg Me!