理解右值和右值引用

基本概念

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.

对右值引用的理解

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

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

你可能感兴趣的:(C/C++)