C++17 中的新表达式求值顺序

new-expression evaluation order in C++17

根据 cppreference/eval_order 规则 12,对分配函数 (operator new) 的调用在(C++17 起)new 表达式中构造函数参数的求值之前排序。因此,我想到了以下

Bar b;
Foo* f = new Foo(b.fun());

在运行时导致首先调用 new,然后在 b 上调用 fun(),最后调用 Foo 的构造函数。 Clang 和 ICC 都会生成此订单。但是 GCC 首先调用 fun(),然后是 operator new,然后是构造函数。

谁是对的?我错过了什么?

查看标准(版本 N4835.pdf):

7.6.2.7 New [expr.new]
23 The invocation of the allocation function is sequenced before the evaluations of expressions in the new-initializer. Initialization of the allocated object is sequenced before the value computation of the new-expression.

在你的例子中,b.fun() 是新初始化器中唯一的表达式。

看起来 Clang、ICC 和 MSVC 做对了,而 GCC 做错了。可能值得询问 GCC 人员并提交错误报告(或者可能已经存在错误报告?)。