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.

+2


source to share


5 answers


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.

+4


source


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



0


source


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).

0


source


Sounds like you want a singleton pattern. This will allow you to create and use one object / instance of a class, but nothing more, even if you access it many times. Cm:

http://www.infernodevelopment.com/singleton-c

-1


source


You can create a service that is static singleton . This service contains all of your object collections and provides functions to access those objects.

-1


source







All Articles