0

I understand that X & const x is redundant. It is not ok! But I want to know what is the difference between X const &x and X & const x? Is the first expression saying that x is a reference to a constant class X ?

Flexo
  • 87,323
  • 22
  • 191
  • 272
bespectacled
  • 2,801
  • 4
  • 25
  • 35

4 Answers4

6

X const &x is a reference to a const X, while X & const x is illegal. There is no such thing as a const reference since references aren't mutable to begin with.

K-ballo
  • 80,396
  • 20
  • 159
  • 169
  • Ironically, putting "mutable" in `backticks` may be read as reference to the very real C++ keyword of that name, which allows one to [change `const` members from inside `const` objects](http://stackoverflow.com/questions/105014/c-mutable-keyword). Not that any of this would make "constant references" any more meaningful or legal (as far as I know, that is). –  Oct 17 '11 at 16:33
  • 1
    @delnan: I added the backticks as a force of habit since `mutable` is indeed a keyword. Should I remove them to avoid confusion? – K-ballo Oct 17 '11 at 16:35
  • Well, it may save a reader or two a second of wonder, but I only added my comment because I found the irony amusing. –  Oct 17 '11 at 16:36
  • @delnan: Let's go with irony then, its worth a second of wonder. – K-ballo Oct 17 '11 at 16:40
5

References themselves are always constant. You cannot change the reference to refer to something else after initialization.

Yes first expression says that the referrence is referring a constant.

Alok Save
  • 202,538
  • 53
  • 430
  • 533
5

Read it from right to left : X& const x - x is a constant reference to object of type X which doesn't make sense, references are constant by definition. X const& x - x is a reference to constant of type X.

a1ex07
  • 36,826
  • 12
  • 90
  • 103
1

X const& if a reference to an X which you are not allowed to modify through the reference. You can think of it as a read-only-view. Whether or not the X itself is const is not reflected in the reference type. Note that you can initialize X const& with both const and non-const objects:

X a;
X const b;
X const& r = a;   // read-only-view on non-const X
X const& s = b;   // read-only-view on const X

The important part is that you cannot change the X through the reference, but you can change a directly, and that change will be reflected via r.

X& const is forbidden by the standard since references themselves can never be modified, anyway.

fredoverflow
  • 256,549
  • 94
  • 388
  • 662