为“左值"命名背后的原因是什么?和“右值"? [英] What is the reasoning behind the naming of "lvalue" and "rvalue"?

查看:60
本文介绍了为“左值"命名背后的原因是什么?和“右值"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C/C ++中命名左值"和右值"的背后是什么原因(我知道它们的功能)?

What is the reasoning behind the naming of "lvalue" and "rvalue" in C/C++ (I know how they function)?

推荐答案

标准提到了这一点:

左值(之所以这么称呼,是因为左值可能出现在赋值表达式的左侧)[...]

An lvalue (so called, historically, because lvalues could appear on the left-hand side of an assignment expression) [...]

右值(之所以称为历史值,是因为右值可能出现在赋值表达式的右侧)[...]

An rvalue (so called, historically, because rvalues could appear on the right-hand side of an assignment expression) [...]

也就是说,您可以分配一个左值,而您可以从其中分配一个右值.

That is, an lvalue was something you could assign to and an rvalue was something you could assign from.

然而,事实与事实之间的距离越来越远.您无法分配的左值的一个简单示例是 const 变量.

However, this has gradually gotten further and further from the truth. A simple example of an lvalue that you can't assign it is a const variable.

const int x = 5;
x = 6; // Error

当涉及运算符重载时,甚至可以在赋值的左侧显示一个右值.

You can even have an rvalue appear on the left side of an assignment when you involve operator overloading.

我发现将左值引用为存储在内存中的对象,将右值引用为一个值(可能已从内存中读取)更有用.这些概念很好地反映了这个想法.一些例子:

I find it more useful to think of an lvalue as referencing an object stored in memory and an rvalue as just a value (that may have been read from memory). The concepts mirror this idea quite well. Some examples:

  • 从左值到右值可以看作是从内存中的对象读取值.
  • 大多数运算符都需要从左值到右值的转换,因为它们使用对象的值来计算结果.
  • 运算符(& )的地址需要一个左值,因为您只能获取内存中某物的地址.不需要获取对象的值即可计算出其地址.
  • 执行 std :: move 将左值表达式转换为右值表达式可以认为是欺骗了编译器,使他们认为存储在内存中的对象实际上只是一个临时值.
  • Lvalue-to-rvalue can be considered the reading of a value from an object in memory.
  • Most operators require lvalue-to-rvalue conversion because they use the value of the object to calculate a result.
  • The address of operator (&) requires an lvalue because you can only take the address of something in memory. It doesn't need to get the value of the object to work out its address.
  • Performing std::move to turn an lvalue expression into an rvalue expression can be thought of as tricking the compiler into thinking the object that's stored in memory is actually just a temporary value.

但是,这并非在所有情况下都成立.只是一个合理的比喻.

However, this also doesn't hold up in every situation. It's just a reasonable analogy.

这篇关于为“左值"命名背后的原因是什么?和“右值"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆