首页 文章详情

C++核心准则ES.44: 不要让执行结果受函数参数的求值次序影响​

面向对象思考 | 392 2020-05-11 23:21 0 0 0
UniSMS (合一短信)

5895d9b3231d3d7d8fcddef504555a5e.webp

ES.44: Don't depend on order of evaluation of function arguments

ES.44: 不要让执行结果受函数参数的求值次序影响


Reason(原因)


Because that order is unspecified.

因为函数参数的求值次序是无定义的。


Note(注意)


C++17 tightens up the rules for the order of evaluation, but the order of evaluation of function arguments is still unspecified.

C++17收紧了运算次序规则,但是函数参数的求值次序依然是无定义的。


Example(示例)

int i = 0;
f(++i, ++i);

The call will most likely be f(0, 1) or f(1, 0), but you don't know which. Technically, the behavior is undefined. In C++17, this code does not have undefined behavior, but it is still not specified which argument is evaluated first.

调用的结果很可能是f(0,1)或者f(1,0),但是不知道会是哪一个。技术上,这个行为是无定义的。在C++17中,这段代码不会是一个无定义的行为,但是依然没有明确那个参数先求值。


Example(示例)


Overloaded operators can lead to order of evaluation problems:

重载的运算符可能引入计算次序的问题。

f1()->m(f2());          // m(f1(), f2())
cout << f1() << f2(); // operator<<(operator<<(cout, f1()), f2())

In C++17, these examples work as expected (left to right) and assignments are evaluated right to left (just as ='s binding is right-to-left)

在C++17中,这些代码示例可以像期待的那样执行(从左向右),同时赋值会从右向左计算(就像赋值运算符=绑定了从右向左计算次序)

f1() = f2();    // undefined behavior in C++14; in C++17, f2() is evaluated before f1()
Enforcement(实施建议)


Can be detected by a good analyzer.

这个问题可以被实现良好的代码解析器检出。


原文链接

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#es44-dont-depend-on-order-of-evaluation-of-function-arguments




觉得本文有帮助?请分享给更多人。

关注微信公众号【面向对象思考】轻松学习每一天!

面向对象开发,面向对象思考!

750d298d2c66bf8b7ba5826f9442641c.webp


good-icon 0
favorite-icon 0
收藏
回复数量: 0
    暂无评论~~
    Ctrl+Enter