看看这个简单的函数调用:
f(a(), b());
根据标准,调用顺序为a()
and b()
未指定。 C++17 有附加规则不允许a()
and b()
交错。据我所知,在C++17之前,没有这样的规则。
现在,看看这个简单的代码:
int v = 0;
int fn() {
int t = v+1;
v = t;
return 0;
}
void foo(int, int) { }
int main() {
foo(fn(), fn());
}
根据 C++17 规则,v
肯定会有这样的价值2
接到电话后foo
。但是,这让我想知道,对于 C++17 之前的版本,是否能保证同样的效果?或者可能是这样v
最终1
?如果不是的话,有什么区别吗int t = v+1; v = t;
,我们只有v++
?
在以前的版本中也不允许函数调用交错。
引用自 C++11 最终草案 (n3337)
1.9 程序执行[执行简介]
...
15. ...
When calling a function (whether or not the function is inline), every value computation and side effect associated with any argument expression, or with the postfix expression designating the called function, is sequenced before execution of every expression or statement in the body of the called function. [ Note: Value computations and side effects associated with different argument expressions are unsequenced. —end note ]
Every evaluation in the calling function (including other function calls) that is not otherwise specifically sequenced before or after the execution of the body of the called function is indeterminately sequenced with respect to the execution of the called function9.
9) 换句话说,函数执行不会相互交错.
在 C++14 版本的最终草案中也可以找到类似的措辞。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)