Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
248 views
in Technique[技术] by (71.8m points)

c++ - Literal initialization for const references

How does the following code work in C++? Is it logical?

const int &ref = 9;
const int &another_ref = ref + 6;

Why does C++ allow literal initialization for const references when the same is not permitted for non-const references? E.g.:

const int days_of_week = 7;
int &dof = days_of_week; //error: non const reference to a const object

This can be explained by the fact that, a non-const reference can be used to change the value of the variable it is referring to. Hence, C++ does not permit a non-const reference to a const variable.

Could this be a possible explanation? C++ does not allow:

int &ref = 7;

Because that is not logical, but:

const int &ref = 7;

Is almost equivalent to:

const int val = 7;

So literal initialization is permitted for const variables.

P.S.: I'm currently studying Lippman's C++ Primer.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

So you can write code like this:

void f( const string & s ) {
}

f( "foobar" );

Although strictly speaking what is actually happening here is not the literal being bound to a const reference - instead a temprary string object is created:

string( "foobar" );

and this nameless string is bound to the reference.

Note that it is actually quite unusual to create non-parameter reference variables as you are doing - the main purpose of references is to serve as function parameters and return values.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...