相关疑难解决方法(0)

是否定义了在聚合初始化期间从后面的成员表达式引用早期成员的行为?

考虑以下:

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)

c++ undefined-behavior language-lawyer c++11 c++14

35
推荐指数
2
解决办法
811
查看次数

标签 统计

c++ ×1

c++11 ×1

c++14 ×1

language-lawyer ×1

undefined-behavior ×1