Search code examples
c++referenceconst-correctness

const reference to non-const object


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?

Solution

  • 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.