Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why int& a = <value> is not allowed in C++?

I am reading about references in C++. It says that int& a = 5 gives compile time error.

In Thinking in C++ - Bruce Eckel, author says that compiler must first allocate the storage for an int and produce the address to bind to the reference. The storage must be const because changing it would make no sense.

I am confused at this point. I am not able to understand the logic behind it. Why can't be change the content in the storage? I understand that it's invalid as per C++ rules, but why?

like image 235
Neeraj Gangwar Avatar asked Oct 15 '13 07:10

Neeraj Gangwar


1 Answers

"The storage must be const because changing it would make no sense."

If you want a be a reference to a const value, you must declare it as const, because a is referencing to a temporary constant value, and changing it is not possible.

const int &a = 123;
a = 1000; // `a` is referencing to temporary 123, it is not possible to change it
          // We can not change 123 to 1000
          // Infact, we can change a variable which its value is 123 to 1000
          // Here `a` is not a normal variable, it's a reference to a const
          // Generally, `int &a` can not bind to a temporary object

For non-const bindings:

int x = 1;
int &a = x;

a is a reference to a lvalue. Simple speaking, it's an alias name for another variable, so on the right hand you should give a variable. The reference a can not change and bind to another variable after it's first binding;

In C++11, you can reference to temporary objects/values by rvalue references:

int &&a = 123;
like image 156
masoud Avatar answered Nov 07 '22 18:11

masoud