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
227 views
in Technique[技术] by (71.8m points)

c++ - const reference can be assigned an int?

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

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

1 Reply

0 votes
by (71.8m points)

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.


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

...