ok , global variable is condemned, singleton is despised, what's the alternative?

mhd picture mhd · Dec 13, 2008 · Viewed 18.2k times · Source

For desktop application that is. This is just a general question that maybe only need general answers.

Answer

Corey Trager picture Corey Trager · Dec 13, 2008

A static class with static data members? But who cares. Static data members are just global variables with more politically correct packaging.

Don't let fashion override your common sense. There's nothing wrong with using a plain old global variable. The singleton pattern is often overkill and annoying to type, and annoying when you are single stepping through code to debug it.

Assuming you are using C/C++, I would recommend that you not have global variables that are class instances that allocate memory from the heap. They will make it harder for you to use tools that check for memory leaks. Declare the global as a pointer, new it at the beginning of main(), delete it at the end.

EDIT AFTER 6 COMMENTS: Think of logging. Wouldn't you want to be able to write a line to your log from anywhere in your app? How concretely do you accomplish that without there being something globally visible to do that logging? If you want something globally visible, then go ahead and make it globally visible.