考虑以下:
struct mystruct
{
int i;
int j;
};
int main(int argc, char* argv[])
{
mystruct foo{45, foo.i};
std::cout << foo.i << ", " << foo.j << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
请注意foo.i在aggregate-initializer列表中的使用.
g++ 5.2.0 输出
45,45
这是明确定义的行为吗?是foo.i在这个聚集型初始化始终保证指存在创建结构的i元素(和&foo.i将指向内存地址,例如)?
如果我添加一个显式构造函数mystruct:
mystruct(int i, int j) : i(i), j(j) { }
Run Code Online (Sandbox Code Playgroud)
然后我收到以下警告:
main.cpp:15:20: warning: 'foo.a::i' is used uninitialized in this function [-Wuninitialized]
a foo{45, foo.i};
^
main.cpp:19:34: warning: 'foo.a::i' is used uninitialized in this …Run Code Online (Sandbox Code Playgroud)