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

I came across a code snippet

const int& reference_to_const_int = 20;
cout<<"
  reference_to_const_int = "<<reference_to_const_int<<endl;     

This code compiles & executes with output :-

reference_to_const_int = 20

This is something strange in for me. As I know reference do not occupy memory & they are aliases to other variables. hence we cannot say

int& reference_to_int = 30;

The above statement shall not compile giving error :-

 error: invalid initialization of non-const reference of type ‘int&’ from an rvalue of type ‘int’

What exactly is happening in the "const int&" case? A full explanation is desired.

Kindly help.

Thanks

See Question&Answers more detail:os

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

1 Answer

A temporary is created, and it's legal to bind a const reference to it, but illegal to bind it to a non-const one.

It's just like:

const int& reference_to_const_int = int(20);  //LEGAL
      int& reference_to_const_int = int(20);  //ILLEGAL

A const reference extends the life of a temporary, that's why this works. It's just a rule of the language.


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