The prefix operators return the object itself as an lvalue. The postfix operators return a copy of the object’s original value as an rvalue.
因此,在这样的语句中 *a++
a 正在递增,并且 a 的原始值的拷贝作为右值返回,但来自左值和右值的 Microsoft C++ 语言引用
An rvalue is a temporary value that does not persist beyond the expression that uses it
并给出了一个例子
// lvalues_and_rvalues1.cpp
// compile with: /EHsc
#include <iostream>
using namespace std;
int main()
{
int x = 3 + 4;
cout << x << endl;
}
In this example, x is an lvalue because it persists beyond the expression that defines it. The expression 3 + 4 is an rvalue because it evaluates to a temporary value that does not persist beyond the expression that defines it.
我的问题:
1) 从 *a++
返回的右值是什么,以便可以取消引用?
2)我是否误解了任何概念?
提前致谢!
最佳答案
The prefix operators return the object itself as an lvalue. The postfix operators return a copy of the object’s original value as an rvalue.
错了!嗯,大部分是这样。如果引用谈论的是所有前缀/后缀运算符,那么它就完全错误了。但是,如果它谈论的是 ++
和 --
前缀/后缀对,那么它是正确的。
现在,考虑到这一点......
what is the rvalue returning from the *a++ so that it can be dereferenced?
假设 a
是某种指针,a++
递增 a
并产生由 a
组成的右值增量之前的值。后缀和前缀形式的递增和递减运算符 ++
和 --
都需要左值作为其运算符。这是因为右值是临时的,也就是说,它们的范围受到它们出现的表达式的限制,因此这些运算符对它们来说意义不大或没有意义。请记住,这些运算符不仅检查/读取,还更改/写入变量本身。
一元 *
运算符采用一个指针(类)对象并取消引用它,产生在其中找到的左值。它适用于右值和左值指针。这是因为 *
可以被视为一种“被动”运算符。它不会更改/写入指针本身,而是取消引用它并返回指针存储的地址处的左值对象,其地址当然是包含在指针。由于 *
需要的只是指针对象中包含的内存地址,而指针本身的地址(如果有的话)在这里是无用的,*
使得对右值和左值都有意义。
您可以认为 *
“需要右值”,并且“必要时左值可以用作右值”,如果它能澄清(或混淆?)事情。
关于c++ - 右值如何取消引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36122689/