// lvalues_and_rvalues2.cppintmain(){int i, j,*p;// Correct usage: the variable i is an lvalue and the literal 7 is a prvalue.// 用法正确:变量i是左值 ,文本7是纯右值 。
i =7;// Incorrect usage: The left operand must be an lvalue (C2106).`j * 4` is a prvalue.// 用法不正确:左操作数必须是左值(C2106)。'j*4'是纯右值。7= i;// C2106
j *4=7;// C2106// Correct usage: the dereferenced pointer is an lvalue.// 用法正确:未引用的指针是左值。*p = i;// Correct usage: the conditional operator returns an lvalue.// 用法正确:条件运算符返回左值。((i <3)? i : j)=7;// Incorrect usage: the constant ci is a non-modifiable lvalue (C3892).// 用法错误:常量ci是不可修改的左值(c3892)。constint ci =7;
ci =9;// C3892}
左值引用声明符: &
保留对象的地址,但行为方式在语法上与对象相似。
语法
type-id & cast-expression
示例
以下示例通过声明 Person 对象和对该对象的引用演示了引用声明符。 由于 rFriend 是对 myFriend 的引用,因此更新任一变量都将更改同一对象。
intmain(){// 正确:i是左值,x是左值引用int i =10;int& x = i;
cout <<"i:"<< i <<" x:"<< x << endl;
i =20;
x =30;
cout <<"i:"<< i <<" x:"<< x << endl;// 错误:非常量引用的初始值必须为左值//int& x = 10; // 10是右值// 正确constint& c =10;}
Output
i:10 x:10 i:30 x:30
反汇编
int i = 10;
00BE5DB2 mov dword ptr [i],0Ah
int& x = i;
00BE5DB9 lea eax,[i]
int& x = i;
00BE5DBC mov dword ptr [x],eax
i = 20;
00BE5E22 mov dword ptr [i],14h
x = 30;
00BE5E29 mov eax,dword ptr [x]
00BE5E2C mov dword ptr [eax],1Eh
伪代码
intmain(){int i =10;int* x =&i;
cout <<"i:"<< i <<" x:"<<*x << endl;
i =20;*x =30;
cout <<"i:"<< i <<" x:"<<*x << endl;}
右值引用声明符: &&
保留对右值表达式的引用。
语法
type-id && cast-expression
示例
#include<iostream>usingnamespace std;intmain(){// 错误:无法将右值引用绑定到左值//int i = 10; // i是左值//int&& x = i;// 正确int&& x =10;
cout <<"x:"<< x << endl;
x =20;
cout <<"x:"<< x << endl;}