C ++ 17排序:赋值左侧的后递增 [英] C++17 sequencing: post-increment on left side of assignment

查看:72
本文介绍了C ++ 17排序:赋值左侧的后递增的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C ++ 17标准通过

The C++17 standard revised the definitions of the order of operations for the C++ language by a rule stating, to the effect:

在每个简单赋值表达式中E1 = E2和每个化合物 赋值表达式E1 @ = E2,每个值的计算和副作用 在每次值计算和E的副作用之前先对E2的序列进行排序 E1

In every simple assignment expression E1=E2 and every compound assignment expression E1@=E2, every value computation and side-effect of E2 is sequenced before every value computation and side effect of E1

但是,在GCC 8.1中使用-std=c++17-Wall

However, when compiling the following code in GCC 8.1 with -std=c++17 and -Wall

int v[] { 0,1,2,3,4,5,6,7 };
int *p0 = &v[0];
*p0++ = *p0 + 1;
cout << "v[0]: " << v[0] << endl;

我收到以下警告:

main.cpp:266:8: warning: operation on 'p0' may be undefined [-Wsequence-point]
     *p0++ = *p0 + 1;
      ~~^~

输出为:

v[0]: 1

问题是:警告是错误的吗?

And the question: is the warning erroneous?

推荐答案

问题是:警告是错误的吗?

And the question: is the warning erroneous?

要视情况而定.

从技术上讲,所讨论的代码是定义明确的.右侧在C ++ 17中先于左侧进行排序,而在不确定地进行排序之前. gcc会在分配后v[0] == 1正确地编译代码.

Technically, the code in question is well-defined. The right-hand side is sequenced before the left-hand side in C++17, whereas before it was indeterminately sequenced. And gcc compiles the code correctly, v[0] == 1 after that assignment.

但是,也不应该编写同样糟糕的代码,因此,尽管警告的特定措词是错误的,但警告的实际精神对我来说似乎还不错.至少,我不会提交有关此问题的错误报告,而且看来这也不值得开发人员花时间去修复. YMMV.

However, it is also terrible code that should not be written, so while the specific wording of the warning is erroneous, the actual spirit of the warning seems fine to me. At least, I'm not about to file a bug report about it and it doesn't seem like the kind of thing that's worth developer time to fix. YMMV.

这篇关于C ++ 17排序:赋值左侧的后递增的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆