C++ refactoring: conditional expansion and block elimination

前端 未结 2 938
无人共我
无人共我 2021-01-19 00:03

I\'m in the process of refactoring a very large amount of code, mostly C++, to remove a number of temporary configuration checks which have become permanantly set to given v

2条回答
  •  耶瑟儿~
    2021-01-19 00:46

    You say:

    Note that although the values are reasonably fixed, they are not set at compile time but are read from shared memory so the compiler is not currently optimising anything away behind the scenes.

    Constant-folding the values by hand doesn't make a lot of sense unless they are completely fixed. If your compiler provides constexpr you could use that, or you could substitute in preprocessor macros like this:

    #define value1() true
    #define value2() false
    #define value3() 4
    

    The optimizer would take care of you from there. Without seeing examples of exactly what's in your headers or knowing how your process of getting these values from shared memory is working, I'll just throw out that it could be useful to rename the existing valueX() functions and do a runtime check in case they change again in the future:

    // call this at startup to make sure our agreed on values haven't changed
    void check_values() {
        assert(value1() == get_value1_from_shared_memory());
        assert(value2() == get_value2_from_shared_memory());
        assert(value3() == get_value3_from_shared_memory());
    }
    

提交回复
热议问题