C++ – Best Practices for Creating a Global Config Class

cstatic-access

I have a large project with a driver part and about 5 libraries doing various associated tasks. Many of the libraries require access to 'global' configuration data which is read from a database at startup by the driver code. By driver I just mean the part which contains the main function.

My idea on how to handle this was to create a config class with a static method to get the config items. Is this the best approach? How else could this be achieved?

eg:

class config {
 public:
   static get_item(key);

 private:
   static values;
};

Is singleton design appropriate here?

Best Answer

The non-singleton way is to create a regular configuration class with regular properties / members, instantiate that object with the correct settings from the database in the driver, and pass the instance to all of the libraries - probably through a std::shared_ptr. This is a common design pattern called Dependency Injection.

That way you avoid all of the potential issues from the singleton design pattern and your code will be more testable as you can instantiate an instance of your configuration class any way you like, with any data, for testing.