Hello i'm trying to figure out this thing..
Say i have this code.
int a = 5;
double& b = a; //Error.
Then once I've declared the second line as a const the compiler doesn't complain anymore.
const double& b = a; //Correct.
what is really going on behind the scene, why const solves the problem.
The const declaration creates a read-only reference to a value. It does not mean the value it holds is immutable—just that the variable identifier cannot be reassigned. For instance, in the case where the content is an object, this means the object's contents (e.g., its properties) can be altered.
Technically speaking, there are no const references. A reference is not an object, so we cannot make a reference itself const. Indeed, because there is no way to make a reference refer to a different object, in some sense all references are const.
Not just a copy; it is also a const copy. So you cannot modify it, invoke any non-const members from it, or pass it as a non-const parameter to any function. If you want a modifiable copy, lose the const decl on protos .
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. Once a reference is bound to refer to an object, it can not be bound to refer to another object.
An int
needs to be converted to double
first. That conversion yields a prvalue temporary and these can't bind to references to non-const.
A reference to const will extend the lifetime of the temporary that would otherwise be destroyed at the end of the expression it was created in.
{
int a = 0;
float f = a; // a temporary float is created here, its value is copied to
// f and then it dies
const double& d = a; // a temporary double is created here and is bound to
// the const-ref
} // and here it dies together with d
If you're wondering what a prvalue is, here's a nice SO thread about value categories.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With