In my program, I’ve got a bunch of classes that will only ever have one created instance for the duration of the program. They are created only once on initialization, and destroyed only once on closing.
These classes all tend to present really broad functionality that is used by many different parts of the program, and so having them as global externs is really clean and easy to understand, rather than encapsulating them in another class or passing around pointers.
The program is multi-threaded, and all of these classes contain their own mutex for access.
Are there any problems with this approach? If so, what are the recommended alternatives.
Use a singleton pattern as follows:
This is completely thread-safe. See here: G++ 4.6 -std=gnu++0x: Static Local Variable Constructor Call Timing and Thread Safety
It is guaranteed by the current standard.
Furthermore this is superior to static initialized global variables because if you have multiple of the above they will be initialized lazily in the correct dependency order.
and in Bar::Bar there is a call to foo(), then the Foo singleton will be created before Bar.
If I had of used global variables:
No such ordering is guaranteed.
3.6.2 Initialization of non-local variables