Non const lvalue references

C++

C++ Problem Overview


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.

C++ Solutions


Solution 1 - C++

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.

Solution 2 - C++

Because making modification on a temporary is meaningless, C++ doesn't want you to bind non-const reference to a temporary. For example:

int a;
double &m = a;  // caution:this does not work.

What if it works?
a is of type int and is being converted to double. So a temporary is created.

You can modify m, which is bound to a temporary, but almost nothing happens. After the modification, variable a does not change (what's worse? You might think a has changed, which may cause problems).

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMarsView Question on Stackoverflow
Solution 1 - C++MaheshView Answer on Stackoverflow
Solution 2 - C++xinnjieView Answer on Stackoverflow