vendredi 29 septembre 2017

Best practice for using global static const objects that are initialised once at the start of the program

I am trying to both corroborate my understanding and perhaps find a more complete solution to this.

Use-case:

Program has to parse a config file that specifies various parameters, if some parameters are missing the default values defined in a header should be used. The object should be created and intialised once at the start and then be available to all objects through the program till its termination. Nothing should be able to change the values inside that object.

I've looked at several questions and there seems to be lots of conflicting solutions, from using singletons to just static const objects. I know the latter will cause duplication as each single unit will have a copy of the content.

So far part of the solution seems to be using extern as shown in c++ global object in combination with declaring it 'const'.

Also, I use c++11. But I welcome answers about future standards (if applicable).

Questions:

1) Can I also make it static?

2) Where should I initialise this static const globalVal?

3) Does this make sense? Are there better ways? I saw that I could also create an object that only gives a const reference to its content. Would that be better?

4) Is this a good way of dealing with this problem? Just want to make sure I am not totally off.

Aucun commentaire:

Enregistrer un commentaire