Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

const reference to non-const object

Tags:

c++

reference

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?
like image 602
user795451 Avatar asked Sep 13 '11 18:09

user795451


2 Answers

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.

like image 141
Oliver Charlesworth Avatar answered Sep 29 '22 11:09

Oliver Charlesworth


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.

like image 31
AnT Avatar answered Sep 29 '22 10:09

AnT