In the following, would there be a temporary object created before const reference is used to a non-const object?
const int y = 2000;
const int &s = y // ok, const reference to const object.
int x = 1000;
const int &r = x; // any temporary copy here?
If no then, how does this work?
const int z = 3000;
int &t = z // ok, why can't you do this?
No.
A reference is simply an alias for an existing object. const
is enforced by the compiler; it simply checks that you don't attempt to modify the object through the reference r
.* This doesn't require a copy to be created.
Given that const
is merely an instruction to the compiler to enforce "read-only", then it should be immediately obvious why your final example doesn't compile. const
would be pointless if you could trivially circumvent it by taking a non-const
ref to a const
object.
* Of course, you are still free to modify the object via x
. Any changes will also be visible via r
, because they refer to the same object.
In
int x = 1000;
const int &r = x;
the right-hand side is an lvalue and the type of x
is the same as the type of the reference (ignoring cv-qualifications). Under these circumstances the reference is attached directly to x
, no temporary is created.
As for "how does this work"... I don't understand what prompted your question. It just works in the most straighforward way: the reference is attached directly to x
. Nothing more to it.
You can't do
const int z = 3000;
int &t = z;
because it immediately violates the rules of const-correctness.
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