“surprising” constant initialization because of definition order

后端 未结 4 2116
醉梦人生
醉梦人生 2021-02-19 11:58

When reading the slides about constexpr the introduction is about \"surprisingly dynamic initialization with consts\". The example is

struct S {
    st         


        
4条回答
  •  名媛妹妹
    2021-02-19 13:05

    I believe that the rules laid out in 3.6.2 to determine when static initialization happens do not include the initialization for d, which is therefore dynamic initialization. On the other hand, S::c is indeed statically initialized (since 5 is a constant expression). Since all static initialization happens before dynamic initialization, you get the expected result.

    To make d eligible for static initialization, it has to be initialized with a constant expression. This in turn forces you to write the S::c inline:

    struct S { static constexpr int c = 5; };
    
    const int d = S::c; // statically initialized
    

    Note that the standard permits dynamic initialization to be replaced by static initialization, which is why reordering the two lines in your original example will cause the two different sorts of initialization. As TonyK points out, you can use array[d] in the static case, but not in the dynamic case, so you can check which one is happening. With the constexpr approach, you're guaranteed to have static initialization and you don't have to rely on optional compiler behaviour.

提交回复
热议问题