如果我的 C++ 类重载了按位或运算符 (|
),C++ 语言规范是否保证传递给该运算符的一系列调用的参数将从左到右求值正确的?还是评估顺序实现已定义(或未定义)?
(IIRC C++ 的内置 |
运算符具有实现定义的求值顺序;但当运算符已为类重载时,情况可能有所不同?)
下面是一个程序,它举例说明了我要问的问题:这个程序是否保证打印出 0 1 2 3 4
(就像我目前坐在的 Mac 上一样),或者它可以在某些环境中合法地打印出 4 3 2 1 0
(或其他一些顺序)吗?
#include <iostream>
class mytype_t
{
public:
mytype_t(int v) : _val(v) {/* empty */}
mytype_t operator | (const mytype_t & rhs) const {return (_val | rhs._val);}
private:
int _val;
};
mytype_t func(int v)
{
std::cout << v << std::endl;
return mytype_t(v);
}
int main(int, char **)
{
mytype_t x = func(0) | func(1) | func(2) | func(3) | func(4);
return 0;
}
最佳答案
如果内置运算符规定了特定的顺序,则参数也会以与重载相同的顺序求值。这是相关段落(来自 n4659,C++17 草案),强调我的:
[over.match.oper]
2 If either operand has a type that is a class or an enumeration, a user-defined operator function might be declared that implements this operator or a user-defined conversion can be necessary to convert the operand to a type that is appropriate for a built-in operator. In this case, overload resolution is used to determine which operator function or built-in operator is to be invoked to implement the operator. Therefore, the operator notation is first transformed to the equivalent function-call notation as summarized in Table 12 (where @ denotes one of the operators covered in the specified subclause). However, the operands are sequenced in the order prescribed for the built-in operator (Clause [expr]).
所以不,重载的 operator|
将没有明确定义的求值顺序,因为内置的没有。
关于c++ - 重载的按位或运算符 ('|' ) 是否具有明确定义的评估顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53513909/