Here’s a common, simple task: Read configuration settings from a configuration file, save the settings (e.g. as a hash) in an object, access this object from various objects that need to access the configuration parameters.
I found this implementation for the ConfigFile class implementation and it works. My question is: what is the best way to make an instance of this class available from my other classes and be thread safe, avoid static initialization order fiasco, etc.
My current approach is to construct it in main() using
// Read face detection related parameter values from the configuration file.
string configFileName = "detection_parameters.txt";
try {
parameters = ConfigFile( configFileName );
}
catch(ConfigFile::file_not_found) {
cerr << "configuration file not found: " << configFileName << endl;
exit(-1);
}
and then make parameters a global variable. But I also read that singletons should be used instead of global variables. How can the singleton be instantiated with the file name?
This must be such a common task that I think there must be a generally accepted good way of doing it? I would appreciate if someone can point me to it.
Thanks,
C
If you’re going to roll-your-own, I would recommend using the Singleton design pattern for your configuration class.
Have the class itself store a static pointer of its own type, and the constructor be private so one would be forced to use the static getter to get the one instance of the class.
so a mock-up (that may not compile, an is missing the fun Config functionality, but should illustrate the point)
In case I’m not being clear, the getConfig() would look at m_configInstance. If it isn’t a valid one, then it would create one (has access to the private constructor) and store it in m_configInstance so every subsequent call would access the same one.
So your main() would use setConfigFileName(), then any class would just have to call Config::getConfig() and then call the operations on it. A lot cleaner than a standard global variable.
Blast – in the time I spent writing this, other people have suggested the singleton design pattern too. Ah well – hope the additional explanation helps.