Template static members initialization order

前端 未结 1 1715
情话喂你
情话喂你 2021-01-21 23:12

I have a question related to a previous question posted here Static field initialization order Suppose I have the following struct, with 2 static members x and

相关标签:
1条回答
  • 2021-01-21 23:32

    This code is safe because Foo<double>::x has constant initialization, but Foo<double>::y has dynamic initialization.

    3.6.2/2:

    Constant initialization is performed:

    • ...

    • if an object with static or thread storage duration is not initialized by a constructor call and if every full-expression that appears in its initializer is a constant expression.

    Together, zero-initialization and constant initialization are called static initialization; all other initialization is dynamic initialization. Static initialization shall be performed before any dynamic initialization takes place.

    On the other hand, if you had:

    double tmp = 1.1;
    
    template <typename T>
    T Foo<T>::x = tmp;
    
    template <typename T>
    T Foo<T>::y = 2.0 * Foo<T>::x;
    

    that code would not be "safe" - Foo<double>::y could end up being either 2.2 or 0.0 (assuming nothing else modifies tmp during dynamic initializations).

    0 讨论(0)
提交回复
热议问题