It's common to hear that the use of global variables is bad practice in C++.
However, I've found them to be fairly common in e.g. Windows API examples. In many cases, it seems like alternative approaches are complex, laborious, or inefficient enough to disfavor their use.
Also, when someone advises against the use of globals, they rarely seem to specify what alternative they feel would be better.
Discussions about globals also frequently use imprecise terminology, and neglect the fact that, strictly speaking, C++ doesn't have globals, just internally/externally linked variables declared outside of functions. (I might be abusing the term here myself.)
I'd like to share an idiom I've found to be useful, and ask for your opinions about this approach:
in foo.cpp:
1 2 3 4 5 6 7 8
|
struct Globals{
Globals();
int bar;
double barbar;
// etc.
} G;
|
Which can then be used as in:
G.bar = 3;
The reasons I like this are:
+ It's quick and simple to use
+ The scope does not pollute other namespaces
+ The constructor provides a very clean and intuitive place to perform initialization
+ It works well with the IDE, allowing you to easily see the list of globals
+ The notation is clear and short
What do you folks think? Is this a bad practice? If so, what else would you suggest?
Cheers