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

Categories

0 votes
213 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...