const variables in header file and static initialization fiasco

后端 未结 4 1895
情歌与酒
情歌与酒 2021-02-02 16:42

After reading a lot of the questions regarding initialization of static variables I am still not sure how this applies to const variables at namespace level.

<
4条回答
  •  借酒劲吻你
    2021-02-02 17:14

    What is referred as the static initialization fiasco is a problem when one namespace level variable depends on the value assigned to a different namespace level variable that might or not be initialized before. In your two examples there is no such dependency and there should not be any problem.

    This, on the other hand, is prone to that type of error:

    // header.h
    extern const std::string foo;
    
    // constant.cpp
    const std::string foo( "foo" );
    
    // main.cpp
    #include "header.h"
    const std::string foobar( foo+"bar" );
    int main() {
       std::cout << foobar << std::endl;
    }
    

    There is no guarantee that foo will be initialized before foobar, even if both are constant. That means that the program behavior is undefined and it could well print "foobar", "bar" or die.

提交回复
热议问题