理解右值和右值引用

本文详细解析了C++中lvalue与rvalue的概念及其应用,包括两者的基本定义、典型示例以及如何使用引用绑定不同类型的值。此外还介绍了C++11引入的rvalue引用以及其在避免不必要的复制和提供完美转发功能方面的作用。

基本概念

lvalue
永久对象,可被取地址,可以出现在 operator= 左侧。
典型的 lvalue:有名称的变量、函数形参(栈中的对象)等。

rvalue
临时对象(即将销毁),不可取地址,只能出现在 operator= 右侧(标准库中有例外,如string、complex 等)。
典型的 rvalue:字面常量(如1、2…等)、匿名对象(临时对象)以及函数的返回值等。另外,也可以通过 std::move 显式地将一个左值转换为右值。

一个表达式的值要么是 lvalue,要么是 rvalue。

An lvalue reference is formed by placing an & after some type.
An rvalue reference is formed by placing an && after some type.

An rvalue reference behaves just like an lvalue reference except that it can bind to a temporary (an rvalue), whereas you can not bind a (non-const) lvalue reference to an rvalue.

  • you can bind a const lvalue reference to an rvalue. (可以将一个右值绑定到一个const 的左值引用)
    • 在C++11之前为了能够将右值(或临时对象)作为引用参数传递给函数,C++标准故意设置了这一个特例:将函数参数声明为 const Type &即可(其中 Type为具体类型)。
  • cannot bind non-const lvalue reference to an rvalue.(不能将一个右值绑定到一个非常量左值引用上)
int &i = 6; // error,lvalue reference 不能引用字面常量	
		    // error: cannot bind non-const lvalue reference of type ‘int&’ to an rvalue of type ‘int’
const int &j = 6; // ok,可以将一个临时对象绑定到一个 const 的左值引用

A &ref_a = A(); 		// error
const A &ref_ca = A();	// ok,可以将一个临时对象绑定到一个 const 的左值引用

int &&rref = 6;		// ok,rvalue reference 可以引用:字面常量
A &&rref_a = A();	// ok,rvalue reference 可以引用:临时对象

rvalue reference 的作用

Rvalue references allow programmers to avoid logically unnecessary copying and to provide perfect forwarding functions.

对右值引用的理解

右值引用左值引用都是引用,都是一个变量(即都是一个左值),左值引用通过在类型名后加 & 来表示,而右值引用则通过在类型名后加 && 表示。只不过左值引用引用的是左值,而右值引用只能引用右值。

函数形参都是左值,因为函数形参都有名称,都可以对形参进行取地址操作。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值