我想知道当两个不同翻译单元中具有静态存储持续时间的两个常量非局部浮点变量之间存在依赖关系时,我是否可以依赖常量初始化 - 其中一个依赖于(初始化为[的值] ) 另一个,对于后者,执行常量初始化。我正在寻找提供和解释标准相关部分的答案,尤其是 C++11 标准。
// Note: the non-use of constexpr is intended (C++03 compatibility)
// foo.h
struct Foo {
static const float kValue;
};
// foo.cpp
const float Foo::kValue = 1.5F;
// bar.h
struct Bar {
static const float kValue;
};
// bar.cpp
#include "foo.h"
const float Bar::kValue = Foo::kValue; // Constant initialization?
// main.cpp
#include "bar.h"
#include <iostream>
int main() { std::cout << Bar::kValue; }
- 非局部(常量)变量
Bar::kValue
,静态存储时长,是否通过常量初始化方式初始化? (依次回答是静态初始化还是动态初始化)
我自己的细节/调查
[basic.start.init]/1 指出[强调我的]:
Constant initializationis performed:
if each full-expression (including implicit conversions) that appears in the initializer of a reference with static or thread storage duration is a constant expression (5.19) and the reference is bound to an lvalue designating an object with static storage duration or to a temporary (see 12.2);
if an object with static or thread storage duration is initialized by a constructor call, and if the initialization full-expression is a constant initializer for the object;
if an object with static or thread storage duration is not initialized by a constructor call and if either the object is value-initialized or every full-expression that appears in its initializer is a constant expression.
如果 Foo::kValue
是常量表达式,则从最后一个项目符号中可以看出,Bar::kValue
是通过常量初始化方式初始化的。我想我可以在 [expr.const] 中找到这是否正确的答案,但我被卡住了。
最佳答案
嗯...我不会相信那个代码,因为我会害怕 static initialization order fiasco . AFAIK,不同编译单元之间静态初始化的顺序是不确定的。这意味着即使是测试也不会让我相信一切都会好起来。
在不深入细节的情况下,我无法在标准中找到任何东西来确保 foo.cpp
中的 Foo::kValue
将在 Bar 之前被初始化
。如果顺序错误,bar.cpp
中的::kValueFoo::kValue
中的值将不确定。
关于c++ - 不同翻译单元中具有静态存储持续时间的依赖非局部常量浮点变量的常量初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56238546/