简体   繁体   English

对左值执行算术运算

[英]Performing arithmetic operations on lvalue

I understood that the following C++ expression 我了解以下C ++表达式

j * 4 = 7; // C2106

is incorrect because an lvalue is expected at the left hand side. 是不正确的,因为期望在左侧有一个左值。

If I guess right, the variable j is infact an lvalue but performing an arithmetic operation j * 4 results in an rvalue. 如果我猜对了,变量j实际上是一个左值,但是执行算术运算j * 4得到一个右值。 Therefore, is it right to say performing an arithmetic operation like addition on an lvalue will always result in an rvalue ? 因此,说对一个左值执行加法运算总是会导致一个右值吗?

If yes, is there any exceptions to this rule? 如果是,此规则是否有例外?

Note : Let us not consider pointers for this question. 注意 :让我们不要考虑此问题的指针。

The built-in operators + (unary and binary), - (unary and binary), * (binary), / , % , << , and >> yield prvalues ("pure" rvalues), without exception. 内置运算符+ (一元和二进制), - (一元和二进制), * (二进制), /%<<>>毫无例外地产生prvalues(“ pure” rvalues)。 (So do various other operators, which you would probably not consider to be arithmetic.) Furthermore, they all require their operands to be prvalues, so if they were originally lvalues, they undergo the implicit lvalue-to-rvalue conversion. (其他各种运算符也是如此,您可能不认为它们是算术的。)此外,它们都要求其操作数是prvalue,因此,如果它们最初是左值,则它们会进行隐式的左值到右值转换。

You're probably aware that the built-in compound assignment operators yield lvalues. 您可能知道内置的复合赋值运算符会产生左值。 A less well-known fact is that the built-in preincrement and predecrement operators also yield lvalues. 一个不太为人所知的事实是,内置的预增和预减运算符也会产生左值。 So perhaps they're counterexample to your hypothesis that arithmetic operations always result in rvalues. 因此,也许它们反驳了您的假设:算术运算始终会导致右值。

If you overload an operator, the value category of its return type can be whatever you wish. 如果重载运算符,则其返回类型的值类别可以是您想要的任何值。 You can make operator+ return T& if you want, where T is some class or enum type. 如果需要,可以使operator+返回T& ,其中T是某些类或枚举类型。 Then the result of an addition could be an lvalue. 那么加法的结果可能是左值。 But it's hard to think of when it would ever make sense to write such an operator. 但是,很难想到何时编写这样的运算符才有意义。

Therefore, is it right to say performing an arithmetic operation like addition on an lvalue will always change it to an rvalue? 因此,说对左值执行加法运算总是将其更改为右值是正确的吗?

Yes. 是。 EDIT: Actually, no. 编辑:其实不。 See other answers. 查看其他答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM