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
?

- 87,323
- 22
- 191
- 272

- 2,801
- 4
- 25
- 35
-
How is `X & const x` redundant? Why it is not ok? – BЈовић Oct 17 '11 at 16:27
-
3@VJo Because the standard says so. Except in cases where it says it's OK. (If the `const` is inserted as the result of a `typedef` or a template expansion, for example.) – James Kanze Oct 17 '11 at 16:30
-
1How can something legal be equivalent to something illegal? :) – fredoverflow Oct 17 '11 at 16:52
-
Ok, I see now. The question was formulated in a weird way. – BЈовић Oct 17 '11 at 17:54
4 Answers
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.

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

- 202,538
- 53
- 430
- 533
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.

- 36,826
- 12
- 90
- 103
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.

- 256,549
- 94
- 388
- 662