C++ Best practices for constants

后端 未结 6 1172
难免孤独
难免孤独 2020-12-09 16:15

I have a whole bunch of constants that I want access to in different parts of my code, but that I want to have easy access to as a whole:

static const bool d         


        
6条回答
  •  北荒
    北荒 (楼主)
    2020-12-09 16:50

    The straight forward way is, to create non const symbols:

    const bool doX = true;
    const bool doY = false;
    const int maxNumX = 5;
    

    These values will be replaced by the compiler with the given values. Thats the most efficient way. This also of course leads to recompilation as soon as you modify or add values. But in most cases this should not raise practical problems.

    Of course there are different solutions:

    • Using static consts, (or static const class members) the values can be modified without recompilation of all refered files - but thereby the values are held in a const data segment that will be called during runtime rather than being resolved at compile tine. If runtime perfomance is no issue (as it is for 90% of most typical code) thats OK.

    • The straight C++ way is using class enums rather than global const identifiers (as noted my Mathieu). This is more typesafe and besides this it works much as const: The symbols will be resolved at compile time.

提交回复
热议问题