gpt4 book ai didi

c++ - 模板静态成员初始化顺序

转载 作者:搜寻专家 更新时间:2023-10-31 01:44:13 25 4
gpt4 key购买 nike

我有一个与此处发布的先前问题相关的问题 Static field initialization order假设我有以下结构,有 2 个静态成员 xy (模板类型本身)

#include <iostream>

using namespace std;

template <typename T>
struct Foo
{
static T x;
static T y;
Foo()
{
cout << "x = " << x << endl;
cout << "y = " << y << endl;
}
};

template <typename T>
T Foo<T>::x = 1.1f;

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


int main()
{
Foo<double> foo;
}

输出:

x = 1.1 
y = 2.2

我初始化 xy以上main() ,你可以看到 y取决于 x , 所以最好是 x首先被初始化。

我的问题:

  1. 在初始化时,x 的类型和 y仍然未知,那么它们什么时候真正初始化?静态成员是否在模板实例化后实际初始化Foo<double> foo;main()
  2. 如果是,声明顺序 xy似乎无关紧要,即我可以先声明 y然后x (在结构和静态初始化中)并且仍然得到正确的输出,即编译器以某种方式知道 y依赖于 x .这是一个明确定义的行为(即符合标准)吗?我在 OS X 上使用 g++ 4.8 和 clang++。

谢谢!

最佳答案

此代码是安全的,因为 Foo<double>::x有常量初始化,但是 Foo<double>::y具有动态初始化。

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.

另一方面,如果你有:

double tmp = 1.1;

template <typename T>
T Foo<T>::x = tmp;

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

该代码将不“安全”- Foo<double>::y最终可能是 2.20.0 (假设在动态初始化期间没有其他内容修改 tmp)。

关于c++ - 模板静态成员初始化顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23841022/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com