Best way to create environment object in C ++
I want to make an environment class accessible from all of my classes in my program, but I don't want to initialize an environment object every time I want to access its members from other classes. What's the best way to get around this in C ++?
I want to do this because I have an environment object that stores all of my configuration values ββthat other classes can use. These values ββare read from several places, including different files. I don't want to parse files every time I create a new environment object in my classes.
source to share
Singleton is not always the solution. While it sometimes seems like a simple solution, it has some disadvantages (like this question ).
How many of your classes really need access to this Environment object? If you literally meant every class you own sounds like your design is flawed.
Quite often, the best alternative to a singleton is to simply convey the object to those around you who really need it.
source to share
What you need to do is wrap the environment class in a Singleton pattern. See this SO question for more information: C ++ Singleton design Pattern
source to share
As already pointed out, what you are looking for is the Singleton pattern. However, the Singleton pattern is often the result of poor design. Whenever you find yourself using the Singleton pattern, or, for that matter, any pattern that essentially requires globals, you should consider whether there might be a better approach to the problem. As for your specific problem, I recommend you take a look at the QSettings class , which is part of the Qt Framework - a free and high quality open source library.
The QSetttings class will allow you to load / save configuration settings using your preferred native mechanism (Windows registry, property list file on Mac OS X, and gconf XML file on Linux). Also, you might want to see my post on Evil Environment Variables if you are considering using environment variables for configuration (the name "environment" for configuration sounds horribly ominous).
source to share