右值和左值之间的精确差异 [英] Exact difference between rvalue and lvalue

查看:210
本文介绍了右值和左值之间的精确差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我阅读 http://thbecker.net/articles/rvalue_references/section_01.html ,我得到了以下snippiest。

While I was reading http://thbecker.net/articles/rvalue_references/section_01.html, I got following snippiest.

// lvalues:
//
int i = 42;
i = 43; // ok, i is an lvalue
int& foo();
foo() = 42; // ok, foo() is an lvalue
int* p1 = &foo(); // ok, foo() is an lvalue

// rvalues:
//
int foobar();
int j = 0;
j = foobar(); // ok, foobar() is an rvalue
int* p2 = &foobar(); // error, cannot take the address of an rvalue
j = 42; // ok, 42 is an rvalue

为什么int * p2 =& foobar是错误语句,而int * p1 =& foo();不是一个错误。

Why int* p2 = &foobar(); is error statement, while int* p1 = &foo(); is not an error. How later one is lvalue while first one is rvalue?

提前感谢

推荐答案

所以我们有两个函数:

int& foo();
int foobar();




  • foo 是返回对引用int的
  • 的函数。
  • foobar 是返回int的函数

    • foo is a function returning lvalue-reference to int
    • foobar is a function returning int
    • 函数调用表达式:

      foobar()
      foo()
      

      都有类型int(引用从表达式中删除,因此 foo )有类型 int ,而不是 lvalue-引用int )。这两个表达式具有不同的值类别:

      both have type int (references are removed from expressions, so foo() has type int and not lvalue-reference to int). The two expressions have different value categories:


      • foobar()函数调用返回非引用的函数是prvalue)

      • foo()是一个左值返回一个左值引用的函数是一个左值)

      • foobar() is a prvalue (a function call to a function returning a non-reference is a prvalue)
      • foo() is an lvalue (a function call to a function returning an lvalue-reference is an lvalue)

      你不能取一个右值的地址的值),因此不允许使用& foobar()

      You can't take the address of an rvalue (a prvalue is a kind of rvalue), so &foobar() is not allowed.

      因此允许& foo()

      这篇关于右值和左值之间的精确差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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