"Global" idiom, and your opinions?

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:
struct 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?

Last edited on
closed account (zb0S216C)
Avoid global storage if possible: http://www.cplusplus.com/forum/general/88920/#msg477397

Last edited on
You had almost invented singletones :)
The problem with globals (aside from optimization and access order hell) arizes when you starts using more complex types as globals or globals depending on other globals.

Singletones avoids it because they are usually lazy initialized and you may be sure that all other dependances are initialized.

Last edited on
Topic archived. No new replies allowed.