tow*_*owi 13 c++ initialization const constexpr c++11
在阅读关于constexpr的幻灯片时,介绍是关于"令人惊讶的动态初始化与consts".这个例子是
struct S {
static const int c;
};
const int d = 10 * S::c;
const int S::c = 5;
Run Code Online (Sandbox Code Playgroud)
唉,音轨缺失了,音符也是如此,所以我只能猜到这里的含义.
是否正确d地"动态地"初始化,因为之前S::c定义了吗? d该声明的S::c是之前d可能是不够的,编译器需要完整的定义,对不对?
那就是说,我怀疑,在下面的例子中d 会静态初始化?
struct S {
static const int c;
};
const int S::c = 5;
const int d = 10 * S::c; // now _after_ defn of S::c
Run Code Online (Sandbox Code Playgroud)
并采取蛋糕,在C++ 11,什么必须是constexpr完全静态初始化?S::c,d或两者兼而有之?
您可以通过尝试声明数组来确定常量是静态初始化还是动态初始化:
struct S {
static const int c;
};
const int d = 10 * S::c; // (1)
const int S::c = 5; // (2)
static char array[d];
Run Code Online (Sandbox Code Playgroud)
此代码在 g++ 版本 4.7.0 中失败,因为d是动态初始化的。如果你交换(1)和(2),它就会编译,因为现在d是静态初始化的。但我找不到另一种方法来修复它,使用constexpr.