在聚合初始化列表的给定位置中,传递给先前位置的值是否可以安全地从相应成员中读取? [英] In a given place in an aggregate initialization list, are values passed into previous places safe to read from the corresponding members?

查看:43
本文介绍了在聚合初始化列表的给定位置中,传递给先前位置的值是否可以安全地从相应成员中读取?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

struct
{
    int a,b;
} s = {5, s.a+1};

根据标准,在上面的示例中读取"s.a"是否安全,以便将s初始化为a = 5和b = 6?如果是这样,大多数编译器是否遵守此规则?

According to the standard, is it safe to read "s.a" in the above example, so that s is initialized to a=5 and b=6? If so, do most compilers obey this rule?

(以上内容在VC10中进行编译.)

(The above compiles in VC10.)

推荐答案

是的,因为聚合成员初始化是按顺序进行的.

Yes, because aggregate member initialization is sequenced.

[dcl.init.aggr] /2具有:

按8.5.4中的初始化器列表初始化聚合时,初始化器列表的元素以递增的下标或成员顺序被用作聚合成员的初始化程序.每个成员是从相应的 initializer-clause 中复制初始化的.

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具有:

括号初始化列表初始化器列表中,初始化器子句,包括由pack产生的任何内容扩展(14.5.3)会按照它们出现的顺序进行评估.也就是说,每次值计算和与给定的 initializer-clause 相关的副作用在每次计算值和副作用之前进行排序与 initializer-list 的逗号分隔列表中跟在其后的任何 initializer-clause 相关的效果.

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关联"em>,因为这是它的完整表达式(因为 initializer-list 不是表达式).

The copy-initialization of an aggregate member is certainly a side effect ([intro.execution]/12), and must be "associated with" the corresponding initializer-clause, because that is its full-expression (since an initializer-list is not an expression).

我尝试过的每个最新的编译器(MSVC,Clang,g ++)都可以正确地编译它.某些旧的编译器可能会弄错(较早版本的g ++以错误的方式对聚合初始化程序进行排序而闻名).

Every up-to-date compiler I have tried (MSVC, Clang, g++) compiles this correctly. It may be possible that some older compilers get it wrong (older versions of g++ were known for getting the sequencing of aggregate initializers wrong).

这篇关于在聚合初始化列表的给定位置中,传递给先前位置的值是否可以安全地从相应成员中读取?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆