gpt4 book ai didi

c++ - 不需要时静态初始化

转载 作者:太空狗 更新时间:2023-10-29 21:20:26 25 4
gpt4 key购买 nike

引自 N3797 C++14 最终工作草案的 3.6.2/3:

An implementation is permitted to perform the initialization of a non-local variable with static storage duration as a static initialization even if such initialization is not required to be done statically, provided that

— the dynamic version of the initialization does not change the value of any other object of namespace scope prior to its initialization, and

— the static version of the initialization produces the same value in the initialized variable as would be produced by the dynamic initialization if all variables not required to be initialized statically were initialized dynamically.

所有变量对一个特定变量的初始化有什么意义?

如果可能,请举例说明后一点。

最佳答案

当一个变量的初始化程序引用另一个变量时,这很重要。

constexpr int f(int);

extern const int a = f(1); // not required to be statically initialized
extern const int b = a; // also not required to be statically initialized

constexpr int f(int x) { return x; }

现在假设实现选择静态初始化b,但动态初始化a。在这种情况下,b 的初始化将在 a 之前进行。您询问的文本解释说这不允许实现将 b 初始化为零:即使 b 首先初始化,它的值也必须是 f( 1),即1

关于c++ - 不需要时静态初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24552283/

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