C ++ input of global variables available for several classes

I am developing a project that takes several command line arguments and uses them as parameters for subsequent simulations. (I want to run a large number of experiments in a batch).

What is the best way to set global variables at runtime? Global in terms: variables can vary over the duration of a run, but must be accessible through a large number of classes.

I am currently reading them in a Config object, which I am including in other classes. If anyone has any better ideas (xml?), I'm all ears.

Thanks!

+6
source share
1 answer

Bring all related variables under one roof for easy access. 2 approaches are possible:

(1) Global namespace spaces

namespace Configuration { extern int i; extern bool b; extern std::string s; } 

(2) Static class members

 class Configuration { // provide proper access specifier static int i; static bool b; static std::string s; } 

To track them correctly, use the getter () - setter () methods as a wrapper in the namespace / class.
With getters-seters, you can handle them in a thread-safe way if the program requires it.

+8
source

Source: https://habr.com/ru/post/913900/


All Articles