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

Why can you do this

int a;
const double &m = a;

But when you do this

int a;
double &m = a;

you get an error?

error: non-const lvalue reference to type 'double' cannot bind to a value of unrelated type 'int'

Edit:

To be more specific I am trying to understand the reason non-const references can't bind temp objects.

See Question&Answers more detail:os

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

1 Answer

That is because a temporary can not bind to a non-const reference.

double &m = a;

a is of type int and is being converted to double. So a temporary is created. Same is the case for user-defined types as well.

Foo &obj = Foo(); // You will see the same error message.

But in Visual Studio, it works fine because of a compiler extension enabled by default. But GCC will complain.


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