c++ - 在 C、C++ 中的初始化中排序

标签 c++ c initialization initializer-list

考虑以下初始化:

/* C, C++ */
int a[] = { f(), g() };
struct { int x, y } foo = { f(), g() };

/* C++ */
struct goo { goo(int x, int y);  };

goo b = { f(), g() };
goo c { f(), g() };    /* C++11 */
goo d ( f(), g() );

f()g() 的执行顺序是否在 C 和 C++ 标准规定的任何行中?

最佳答案

在这两种情况下

goo b = { f(), g() };
goo c { f(), g() };    /* C++11 */

评估顺序是从左到右确定的,所有副作用都应在下一个初始化程序之前应用。

来自 C++ 标准

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.

但是在 C 中还有其他规则

The evaluations of the initialization list expressions are indeterminately sequenced with respect to one another and thus the order in which any side effects occur is unspecified.

关于c++ - 在 C、C++ 中的初始化中排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22515685/

相关文章:

c++ - 使用宏使用额外的元素初始化数组

c - C语言中如何将数组清空?

c++ - 无符号整数如何工作

c++ - 如何在另一个 C++ 程序中运行一个 C++ 程序?

可变类型列表前缀的 c++ std::tuple

c - C 中的 UMASK 函数

c - 检测宏中的整数常量表达式

c++ - Newb C++类问题

c - C 与 Python/numpy 的数学表现较差

iOS swift : init not being fired?