c++ - 在聚合初始化列表中的给定位置,传递到先前位置的值是否可以安全地从相应成员读取?

标签 c++ aggregate-initialization

<分区>

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/

相关文章:

c++ - std::pair 与引用和引用包装器之间有什么区别

c++ - 逐字段构造函数生成的规则是什么?

c++ - 聚合初始化原子成员

c++ - 用于聚合结构初始化时的三元运算符整数表达式的类型

c++ - 为什么要使用静态函数模板?

c++ - 不确定如何修复 "Member reference"错误

python - 我们可以使用Microsoft SEAL/PySEAL库对加密数据进行除法运算吗

c++ - 让程序每小时在 MFC C++ 中运行某些函数

c++ - 聚合初始化在 C++11 中何时有效?

c++ - 使用聚合初始化和成员初始化器初始化结构