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, cons开发者_开发问答t 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.
The understanding on the Reference (&) answers this question..
Reference is just an alias to the variable that it is assigned to it..
And const is a constraint imposed by the compiler to the variable that is declared as const
int x = 1000;
const int &r = x;
In this case, its a const reference to a non const variable. So you cannot change the data of x with reference variable r(just acts a read only).. yet you can still change the data x by modifying x
const int z = 3000;
int &t = z
In this case, non const reference to const member which is meaningless. You are saying reference can allow you to edit a const member(which is never possible)..
So if you want to create a reference for a const member, it has to be like the first case you mentioned
const int z = 3000;
const int &t = z;
精彩评论