Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

const reference parameters

Tags:

c++

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.


Yes there is! the first one is more readable :)


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.


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.