References to const

1.
If we want to bind a reference to an object of a const type.
To do so we must use a reference to const.

const int a=1;
const int &r=a;

error:
int &r1=a;

const references is a reference to const?
Technically speaking, there are no const references. A reference is not an object, so we cannot make a reference itself const.

2.
It is important for us to realize that a reference to const restricts only what we can do through that reference. Thus, we can bind a reference to const to a nonconst object, a literal, or a more general expression.

e.g.
int i=1;
int &r1=i;
const int &r2=i;

3.
When we bind a reference to an object of a different type, what will happen?

e.g.
double dval=3.14;
const int &r1=dval;

To ensure that the object to which ri is bound is an, the compiler transforms this code into sometime like

const int temp=dval;
const int &ri=temp;

In this case, ri is bound to a temporary object.
Obviously, this initialization is not allowed.

If ri is not const, what will happen?
Doing so will change the object to which ri is bound, but the object is a temporary, not dval.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值