Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...