Reputation:
Is there a difference between the following declarations?
void somefunc(const Person &p);
void somefunc(Person const &p);
Upvotes: 73
Views: 44336
Reputation: 64672
See this http://www.parashift.com/c++-faq-lite/const-correctness.html
(See new link instead : https://isocpp.org/wiki/faq/const-correctness#const-ref-alt)
Specifically 18.6 to 18.8.
[18.6] What does "const Fred& x" mean?
It means x aliases a Fred object, but x can't be used to change that Fred object.
[18.7] Does "Fred& const x" make any sense?
No, it is nonsense.
[18.8] What does "Fred const& x" mean?
Fred const& x is functionally equivalent to const Fred& x. However, the real question is which should be used.
Read the rest of the article for more info. But essentially, it says they are equivalent, and you can use either one as you see fit. However, you should pick one and stick with it, to avoid future confusion.
Upvotes: 11
Reputation: 90422
there is no difference. const
binds to the type to its left...unless it is the first part of the declaration in which case it binds to the right.
See: https://isocpp.org/wiki/faq/const-correctness#const-ref-alt
Personally, I find that const T &x
reads better. According to this, Bjarne also prefers to put the const
first. Specifically because the keyword was originally going to be called readonly
and readonly int x
reads better :-P.
Upvotes: 92
Reputation: 10863
Both are the same.
const Person & x is currently the most popular, because English puts adjectives before the nouns, and that makes it "more English like."
The alternative form, Person const & x, was suggested as a less idiomatic form. Their argument was that that form can always be parsed from right to left, "x is a reference to a const Person." The argument was that clarity of parsing was more important than idiomatic structure.
Unfortunately for those people, their form doesn't handle everything. Once you start seeing arrays and function pointers and other exotic forms, the rules start to break down. char *str[10] cannot be written in right to left form because the array has to be on the right side. void (*signal(int, void (*fp)(int)))(int) makes the right to left people cringe in pain.
Only rule has ever cropped up to make sense of all types, the Clockwise Spiral rule: http://c-faq.com/decl/spiral.anderson.html
Usually, once someone sees the the clockwise spiral, all hopes of a a clear parsing rule goes out the window. Most people then accept that const Person& x is probably the best way to go!
Upvotes: 4
Reputation:
It really is a matter of taste.
If read from right to left, "Person const & x
" reads "x is a reference to a constant Person."
This sounds better than "const Person & x
", which would be "x is a reference to a Person, which is constant."
So if one is familiar with the right-to-left reading direction of variable declarations, one perhaps would prefer the first one.
Upvotes: 3