References to const

来源:互联网 发布:iphone网络不可用 编辑:程序博客网 时间:2024/06/08 00:59

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.

0 0
原创粉丝点击