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
int& a = 5;
In order for the above code to work, int&
needs to bind to a temporary object of type int
created out of the expression 5
. But binding int&
to a temporay didn't appeal to Bjarne Stroustrup — and he gave an example, similar to the following, to illustrate his point:
void f(int &i) { ++i; }
float x = 10.0;
f(x);
std::cout << x <<< std::endl;
What will the std::cout
print1? Looks like it will print 11
.
It feels, ++i
is changing the argument x
, but it doesn't. This is one reason why the creator of C++ didn't permit temporaries to bind to non-const reference.
However, you can do this:
int const & i = 10;
int const & j = x; //x is float
And since C++11, you can do this:
int && i = 10;
int && i = x; //x is float
Hope that helps.
1. assuming int&
can bind to the temporary created out of x
.
"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;
What you can do is
int b=5;
int &a=b;
or
const int& a = 5;