本文介绍了左/右值用于前/后缀增量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

学习左值和右值.定义可以是地址",是左值,否则是右值.

我检查了运算符的优先级,前缀和后缀的增加都比运算符的地址"具有更高的优先级.

对于以下两个示例,谁能解释一下为什么第一个& value1 ++"是左值,而第二个& value1 ++"是右值.

我对这两种情况的错误理解是:pValue1指向value1变量.无论在建立地址相关之前或之后将value1更改为8,value1变量始终占据一个存储位置,我们可以导出其地址,对吗?

  int值1 = 7;int * pValue1 =& ++ value1;int * pValue1 =& value1 ++; 
解决方案

根据我的评论,您可以看到为什么编译器反对这种操作.问题在于后缀 operator ++ 的一般实现,该实现复制对象(在这种情况下为 int ),递增原始对象并返回预先递增的副本.您可以将其想像为通过以下方式定义的函数:

  int foo_operator(int& a){int复制= a;+ = 1;返回副本;} 

如果您尝试在示例中使用该函数,则编译器也会对此提出抗议.该函数的返回值为 rvalue .

您现在可能会问-前缀为 operator ++ 的功能是什么?这不是返回值的函数吗?答案是-.前缀 operator ++ 返回引用,而不是复制的值,因此它的结果"可以与操作数& 一起使用./p>

Learning the lvalue and rvalue. The definition is whatever that can be "address of" is the left value and otherwise, it is rvalue.

I checked the operator precedence, both prefix and postfix increment has higher priority than the "address of" operator.

For the following two examples, can anyone explain a bit why the first one "&++value1" is a lvalue while the second one "&value1++" is a rvalue.

My wrong understanding for both case is: pValue1 is pointing to the value1 variable. No matter value1 is changed to 8 before or after the address correlation is built, the value1 variable always occupies one memory location and we can derive its address, right?

int value1=7;

int *pValue1=&++value1;

int *pValue1 = &value1++;
解决方案

Based on my comment you can see why the compiler is against this kind of operation. The problem lies in general implementation of postfix operator ++, which copies the object (int in this case), increments the original one and returns that preincremented copy. You can think of it like of a function that is defined in following way:

int foo_operator(int& a)
{
    int copy = a;
    a += 1;
    return copy;
}

If you try to use that function in your example, your compiler will also protest against it. The return value of that function is an rvalue.

You might now ask - what's up with the prefix operator ++? Isn't that also a function that returns a value? And the answer would be - no. Prefix operator ++ returns a reference, not a copied value, thus the 'outcome' of it can be used with operand &.

这篇关于左/右值用于前/后缀增量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 12:55