c++ - C++ 中运算符 = 的操作数的顺序是怎样的?

标签 c++ standards c++14

在下面的代码中:

A & getDataA() ;
B & getDataB() ;

void foo()
{
   getDataA() = getDataB() ;
}

getDataA() 是否保证在 getDataB() 之前或之后进行计算,或者两个操作数的计算相对于另一个操作数是否不按顺序排列?

注意:我对引用标准的答案感兴趣。

.

P.S.:到目前为止我的研究...

我试图理解标准来寻找答案,这是我的研究结果。我的理解是两个操作数的求值是无序的。

但是...(每个引用均来自 C++14 草案 n3797, 5.17 [expr.ass]):

The assignment operator (=) and the compound assignment operators all group right-to-left.

这意味着表达式 a = b = c ; 实际上是 a = (b = c) ;

In all cases, the assignment is sequenced after the value computation of the right and left operands, and before the value computation of the assignment expression.

第一部分表示对于 a = b ;,实际的赋值将在 ab 求值之后发生。第二部分让我困惑:我可以理解 operator += (或另一个复合赋值运算符),但我不能理解 operator =

查看本章的开头(5 表达式 [expr]),我读到:

Uses of overloaded operators are transformed into function calls as described in 13.5. Overloaded operators obey the rules for syntax specified in Clause 5, but the requirements of operand type, value category, and evaluation order are replaced by the rules for function call.

这让我相信在 AB 的情况下,两个操作数的计算是无序的(函数参数的计算是无序的,除非我错过了一些东西) > 不是内置的。

但是在上面的例子中,AB可能是int,所以内置的运算符= 将被调用,而不是函数。

最佳答案

考虑 §1.9 中的这段文字:

Several contexts in C++ cause evaluation of a function call, even though no corresponding function call syntax appears in the translation unit. […] The sequencing constraints on the execution of the called function (as described above) are features of the function calls as evaluated, whatever the syntax of the expression that calls the function might be.

这特别适用于以下来自 [expr]/2 的引用(您也引用了自己):

Overloaded operators obey the rules for syntax specified in Clause 5, but the requirements of operand type, value category, and evaluation order are replaced by the rules for function call.

假设A是一个类,则赋值是对其operator=的隐式调用:

getDataA().operator=( getDataB() );

根据 [expr.call]/8 的(非规范)注释:

[ Note: The evaluations of the postfix expression and of the argument expressions are all unsequenced relative to one another. […] — end note ]

规范性文本位于此答案的初始引用上方,其中隐含了以下内容:

Except where noted, evaluations of operands of individual operators and of subexpressions of individual expressions are unsequenced.

没有任何地方说明函数调用中参数和后缀表达式的求值顺序。

关于c++ - C++ 中运算符 = 的操作数的顺序是怎样的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26694842/

相关文章:

c++ - 虚拟继承会增加派生类的大小吗?

c++ - 字节真的是最小可寻址单位吗?

c++ - 多线程和共享资源:使用C++定期将数据从缓冲区(数据结构)复制到文件

c++ - 二叉搜索树中节点/值的频率

c++ - gdb:选定框架上的信息局部信息

c++ - 将没有定义的 static const int 的地址传递给模板是否合法?

php - 如何在库中提供日志记录 api

c++ - 为什么这个范围基于语句返回一个太低的数字?

c++ - header 中的字符串——这是否违反了 ODR?

c++ - 一直在尝试在 C++ 中将 12 小时时钟格式转换为 24 小时时钟格式