Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Non const lvalue references

Tags:

c++

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.

like image 411
Mars Avatar asked Sep 02 '13 03:09

Mars


People also ask

What is non const reference?

Whether a reference refers to a const or nonconst type affects what we can do with that reference, not whether we can alter the binding of the reference itself." I think this means that making a reference a "const" when it is referenced to a non const object does absolutely nothing.

Is const reference an lvalue?

Such a reference is called an lvalue reference to a const value (sometimes called a reference to const or a const reference). In the above program, we bind const reference ref to modifiable lvalue x . We can then use ref to access x , but because ref is const, we can not modify the value of x through ref .

Can lvalue bind to rvalue reference?

An lvalue reference can bind to an lvalue, but not to an rvalue.

What is const reference in C++?

- const references allow you to specify that the data referred to won't be changed. A const reference is actually a reference to const. A reference is inherently const, so when we say const reference, it is not a reference that can not be changed, rather it's a reference to const.


Video Answer


2 Answers

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.

like image 177
Mahesh Avatar answered Sep 19 '22 23:09

Mahesh


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).

like image 29
xinnjie Avatar answered Sep 18 '22 23:09

xinnjie