constant initialization
该页由英文版wiki使用Google Translate机器翻译而来。
该翻译可能存在错误或用词不当。鼠标停留在文本上可以看到原版本。你可以帮助我们修正错误或改进翻译。参见说明请点击这里. |
Sets the initial values of the static constants
目录 |
[编辑] 语法
static T & ref = constexpr;
|
(1) | ||||||||
static T object = constexpr;
|
(2) | ||||||||
[编辑] 解释
Constant initialization is performed after zero initialization of the static and thread-local objects and before all other initialization. Only the following variables are constant initialized:
The effects of constant initialization are the same as the effects of the corresponding initialization, except that it's guaranteed that it is complete before any other initialization of a static or thread-local object begins, and it may be performed at compile time.
The object that was initialized by constant initialization can be used in constant expressions, e.g. in an array declaration.
[编辑] 注释
The compiler is permitted to initialize other static and thread-local objects using constant initialization, if it can guarantee that the value would be the same as if the standard order of initialization was followed. Such objects can be used in constant expressions, but this use is not portable.
[编辑] 示例
#include <iostream> #include <array> struct S { static const int c; }; const int d = 10 * S::c; // not a constant expression: S::c has no preceding // initializer, this initialization happens after const const int S::c = 5; // constant initialization, guaranteed to happen first int main() { std::cout << "d = " << d << '\n'; std::array<int, S::c> a1; // OK: S::c is a constant expression // std::array<int, d> a2; // error: d is not a constant expression }
输出:
d = 50