C++复习Lvalues,Rvalues,References

本文详细介绍了C++11中lvalue引用和rvalue引用的概念及其用法。通过实例展示了如何利用引用避免对象复制,提高程序效率。同时,文章还探讨了在函数声明和返回值中使用引用的语法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

An lvalue is an expression that identifies a non-temporary object. An rvalue is an expression that identifies a temporary object or is a value (such as a literal constant) not associated with any object. As a general rule, if you have a name for a variable, it is an lvalue, regardless of wherther it is modifiable.

In C++11, we can have two types of references: lvalue references and rvalue references.

In c++11, an lvalue reference is declared by placing an & after some type. An lvalue reference then becomes a synonym(i.e.,another name)for the object it references.

In C++11,an rvalue reference is declared by placing an && after some type. An rvalue reference has the same characteristics as an lvalue reference except that. inlike an lvalue reference, an rvalue reference can also reference an rvalue(i.e.. a temporary).

lvalue references use 

  1. aliasing complicated names.///copy.   auto & whichList = theLists[ myhash( x , theLists.size())];

  2. range for loops.////for(auto & x: arr)  ++x;

  3. avoiding a copy.///auto &x=findMax(arr);///if auto is not used. the typically a non-modifiable reference is explicitly stated with const;

This code illustrates two important concepts:

  1. Reference variables are often used to avoid copying objects avoid copying objects across function-call boundaries(either in the function call or the function return).

  2. Syntax is needed in function declarations and returns to enable the passing and returning using references instead of copies.

  3. 我自己写的小网站www.caozhicong.com

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值