这个问题在这里已有答案:
如果我有一个用存储声明的变量,即int x;并通过调用constexpr函数对其进行初始化,它将在main开始执行任何代码之前确定其值。
constexpr int get_value() { return 5;}
int x = get_value();
int main() {
return x;
};
在C ++ 20中,你有constinit
:
constexpr int get_value() { return 5;}
// Still mutable, not constexpr but
// initialized with a value at compile time.
constinit int x = get_value();
int main() {
return x;
};