“surprising” constant initialization because of definition order

后端 未结 4 2104
醉梦人生
醉梦人生 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:54

    For static initialization one needs, roughly speaking, a constant-expression initializer.

    To be a constant-expression, roughly speaking, a variable needs to be of a const type and have a preceding initialization with a constant-expression.

    In the first example d's initializer is not a constant-expression, as S::c isn't one (it has no preceding initialization). Hence, d is not statically initialized.

    In the second example d's initializer is a constant-expression, and everything is OK.

    I'm simplifying matters. In full formal standardese this would be about nine times longer.


    As for constexpr specifier, no object has to be declared constexpr. It is just an additional error-check. (This is about constexpr objects, not constexpr functions).

    You may declare S::c constexpr in the second variant if you want some extra error protection (perhaps 5 will start changing its value tomorrow?) Adding constexpr to the first variant cannot possibly help.

提交回复
热议问题