对函数参数的要求是否也适用于初始值设定项列表?

Do the Requirements Placed on Function Arguments Also Apply to Initializer Lists?

本文关键字:列表 适用于 参数 函数 是否      更新时间:2023-10-16

所以我在这里读到: https://stackoverflow.com/a/598150/2642059 这是非法的:

foo(i++, i++);

但我相信这是因为没有强制序列,据我所知,初始值设定项列表就是这种情况。那么这是法典吗?

const int foo[] = { i++, i++ };

是的,初始值设定项子句的求值顺序在大括号初始化列表中得到保证。

从标准 §11.6.4/4 列表初始化 [dcl.init.list]:

(强调我的)

在大括号初始化列表的初始值设定项列表中, 初始值设定项子句,包括由包扩展产生的任何子句, 按其显示顺序进行评估。也就是说,每个值 与给定初始值设定项子句相关的计算和副作用 在每个值计算和相关副作用之前进行排序使用逗号分隔的任何初始值设定项子句 初始值设定项列表的列表。[ 注意:此评估顺序成立 无论初始化的语义如何;例如,它 当初始值设定项列表的元素被解释为 构造函数调用的参数,即使通常没有 对调用参数的排序约束。— 尾注 ]

从 cppreference.com:

每个初始值设定项子句都按顺序排序 在任何之前 在大括号初始化列表中跟随它的初始值设定项子句。这是在 与函数调用的参数对比 表达 哪些是 未排序。

标准说明示例,

struct A { A(int, int) {} };
...
int i = 0;
A a1(i++, i++); // used as the arguments of the constructor; unsequenced
A a2{i++, i++}; // used as the arguments of the constructor; sequenced, within the initializer-list of a braced-init-list