“surprising” constant initialization because of definition order

后端 未结 4 2105
醉梦人生
醉梦人生 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 12:44

    You can find out whether a constant is statically or dynamically initialised by trying to declare an array:

    struct S {
        static const int c;
    };
    const int d = 10 * S::c; // (1)
    const int S::c = 5;      // (2)
    
    static char array[d];
    

    This code fails in g++ version 4.7.0, because d is dynamically initialised. And if you exchange (1) and (2), it compiles, because now d is statically initialised. But I can't find another way to fix it, using constexpr.

提交回复
热议问题