前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++核心准则ES.44: 不要让执行结果受函数参数的求值次序影响​

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

作者头像
面向对象思考
发布2020-05-20 00:15:40
2890
发布2020-05-20 00:15:40
举报

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

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2020-05-11,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 面向对象思考 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Enforcement(实施建议)
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档