<分区>
struct
{
int a,b;
} s = {5, s.a+1};
按照标准,在上面的例子中读取“s.a”是安全的,所以s被初始化为a=5和b=6吗?如果是这样,大多数编译器都遵守这条规则吗?
(以上在VC10编译。)
<分区>
struct
{
int a,b;
} s = {5, s.a+1};
按照标准,在上面的例子中读取“s.a”是安全的,所以s被初始化为a=5和b=6吗?如果是这样,大多数编译器都遵守这条规则吗?
(以上在VC10编译。)
最佳答案
是的,因为聚合成员初始化是有序的。
[dcl.init.aggr]/2 有:
When an aggregate is initialized by an initializer list, as specified in 8.5.4, the elements of the initializer list are taken as initializers for the members of the aggregate, in increasing subscript or member order. Each member is copy-initialized from the corresponding initializer-clause.
[dcl.init.list]/4 有:
Within the initializer-list of a braced-init-list, the initializer-clauses, including any that result from pack expansions (14.5.3), are evaluated in the order in which they appear. That is, every value computation and side effect associated with a given initializer-clause is sequenced before every value computation and side effect associated with any initializer-clause that follows it in the comma-separated list of the initializer-list.
聚合成员的复制初始化当然是一个副作用([intro.execution]/12),并且必须“关联”相应的initializer-clause,因为那是它的完整表达式(因为initializer-list 不是表达式)。
我尝试过的每个最新编译器(MSVC、Clang、g++)都能正确编译它。一些较旧的编译器可能会弄错(较旧版本的 g++ 以错误的聚合初始化程序顺序而闻名)。
关于c++ - 在聚合初始化列表中的给定位置,传递到先前位置的值是否可以安全地从相应成员读取?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21294831/