What is the difference between the arguments in:
int foo1(const Fred &arg) {
...
}
and
int foo2(Fred const &arg) {
...
}
? I don't see this case covered in the parashift FAQ.
What is the difference between the arguments in:
int foo1(const Fred &arg) {
...
}
and
int foo2(Fred const &arg) {
...
}
? I don't see this case covered in the parashift FAQ.
No difference, both are syntactically and semantically same.
Though they are one and the same, to retain consistency with the RIGHT-LEFT rule about parsing C and C++ declarations, it is better to write Fred const &arg
Also refer this for developing more understanding about declarations, qualifiers and declarators.
No difference as const is read right-to-left with respect to the &, so both represent a reference to an immutable Fred instance.
Fred& const
would mean the reference itself is immutable, which is redundant; when dealing with const pointers both Fred const*
and Fred* const
are valid but different.
It's a matter of style, but I prefer using const
as a suffix since it can be applied consistently including const member functions.
References doesn't work the same way as pointers: for pointers you can have 'const pointers' (type * const p
) and 'pointer to const' (const type * p
or type const * p
).
But you don't have this for references: a reference will always refer to the same object; in that sense you can consider that 'references' are 'const references' (the same way you can have 'const pointers').
Therefore something like 'type & const ref' is not legal. You can only have 'reference to type' (type &ref
) and 'reference to constant type' (const type &ref
or type const &ref
; both are exactly equivalent).
One last thing: even if const type
sounds more correct in English, writing type const
allows a more systematic understanding of declarations "right to left" : int const & ref
can be read has 'ref is a reference to a constant int'. Or more complicated example: int const * const & ref
, ref is a reference to a constant pointer to a constant int.
Conclusion: in your question, both are exactly equivalent.
I'll dissent from a lot of the other answers and prefer const T&
(and const T*
):
const T*
seems way more common to me than T const*
in all of the C code I've seen. (It's the style used in K&R's The C Programming Language and the style used in the C standard.)const T&
has way more inertia than T const&
, and I think following common practices is more readable than dogmatically adhering to right-to-left parsing rules. (I don't agree that const T&
breaks that rule anyway.)T const*
, it seems easier to misenter it as T* const
(especially if people aren't as accustomed to it).