Why do some people prefer "T const&" over "const T&"?
So, I realize that const T&
and T const&
are identical and both mean a reference to a const T. In both cases, the reference is also constant (references cannot be reassigned, unlike pointers). I've observed, in my somewhat limited experience, that most C++ programmers use const T&
,开发者_运维问答 but I have come across a few people who use T const&
. I use const T&
simply because I learned it that way, and so T const&
looks a little bit funny to me. What is the reason that you use the variant that you use? Do any of you work at an organization for which the coding standards mandate the use of one variant over the other?
Edit
Based on the answers, it would appear that one reason for choosing between the two is whether you want to read it like the compiler (right-to-left) or like English (left-to-right). If one reads it like the compiler, then "T const&" reads as "& (reference) const (to a constant) T (of type T)". If one reads it like English, from left-to-right, then "const T&" is read as "a constant object of type T in the form of a reference". I prefer to read it like English prose, but I can certainly see the sense in interpreting it the way that the compiler does.No one has answered the organization or coding standards question, but I strongly suspect that most organizations do not mandate one over the other, although they might strive for consistency.
I think some people simply prefer to read the declarations from right to left. const
applies to the left-hand token, except when there is nothing there and it applies on the right-hand token. Hence const T&
involves the "except"-clause and can perhaps be thought more complicated (in reality both should be as easy to understand).
Compare:
const T* p; (pointer to T that is const)
T const* p; (pointer to const T) //<- arguable more natural to read
T* const p; (const pointer to T)
This will make a difference when you have more then one const/volatile modifiers. Then putting it to the left of the type is still valid but will break the consistency of the whole declaratiion. For example:
T const * const *p;
means that p is a pointer to const pointer to const T and you consistenly read from right to left.
const T * const *p;
means the same but the consistency is lost and you have to remember that leftmost const/volatile is bound to T alone and not T *.
If you find this discussion interesting, you'd probably find this article by Dan Saks interesting. It doesn't directly address your question, but explains why he prefers
VP const foo[];
to
const VP foo[];
It's because given
typedef void *VP;
you could easily be misled into thinking that the second example above means
const void *foo[]; // Wrong, actually: void *const foo[];
but the first example is harder to misinterpret.
My reasoning is as follows:
It does seem to roll off the tongue better if you write "const T&" but when you do that you end up with the ambiguous, "constant T reference." I've seen this cause problems more than once in the understandability of code that allowed someone, even semi-experienced, to misinterpret what something meant or how to declare a more complex type.
I can't think of any example right now but more than once I've answered questions about type declarations and constness where the problem was caused by the habit of using "const T &" instead of "T const &". I used to write it that way as well and when I became a Sr. Developer, someone in charge of mentoring and creating code standards in projects, I found it much easier for entry level developers when I force everyone to use "T const&". I suppose one rather trivial, rookie mistake would be why does this code compile?
const T* t = f();
t = 0; // assignment to const?? - no, it is not the T* that is const, just the T.
When you learn to read it the way that the compiler does it becomes much easier to understand what any given complex type is as well as allowing you to more readily declare complex types when you need to. By complex types I'm talking about things such as:
T const * const &
When you know that the compiler reads right to left, inside to out, what that means becomes quite apparent and when it is necessary to write one you can do so easily: reference to constant pointer to a constant T. Now write the declaration of a "reference to a pointer to a constant pointer to a T". If you simply use left to right notation I think you'll find this quite easy.
In short, though it initially seems unnatural teaching oneself to use right->left grammar ALL the time, instead of only when it is required (because it often is), you'll find it much easier to remember what a line of code means and how to write what you mean. It's sort of along the same lines of why I disallow "," in declarations:
T* ptr1 = 0, ptr2 = 0; // oops!!!
// do it this way please!
T* ptr1 = 0;
T* ptr2 = 0;
Technically it's all the same but when you try to get a bunch of people of varying capacities working on the same thing you'll tend to make sure everyone uses whatever method is the easiest to understand and use. My experience has taught me that "T const&" is that method.
I think is personal preference. There is no difference between the two variants.
Being as code is predominantly English-based, programmers tend to read left to right, so const T&
reads naturally to us where the compiler reads it inside out right to left so T const&
reads naturally(reference to a const T)
That's because some find it helpful to read the declaration right-to-left.
char const*
const char*
are both pointer to const char.
I used to be a strong advocate of const T&
because it does read logically left-to-right (it's a constant T reference). (And probably there's some bias since most code I'd encountered to that point was written that way.)
Over the years I've encountered some corner cases (such as multiple pointer/reference layers, multiple variable declarations, and method pointers) which strain things a little for the reasons other people have already answered. Often introducing additional typedefs help you "unstick" these cases to some extent, but then you have to come up with a name for something even if it's only used once.
The tipping point for me was the introduction of auto
in C++11, especially when combined with range-based-for. With that, I've flipped and now strongly prefer T const&
(or "reference to constant T", reading right to left) instead. Not only is it more consistent with how the compiler actually parses, it means that when you replace the type with auto
, this always ends up at the left, which I think reads better.
Compare:
for (const T& a : list) for (T& a : list)
for (T const& a : list) for (T& a : list)
for (const auto& a : list) for (auto& a : list)
for (auto const& a : list) for (auto& a : list)
Note also the column on the right, where I've added the non-const version of the same. At least for me, the const vs. non-const and auto vs. explicit all seem most consistent in the cases where const
appears after T.
But this is a style choice, and as such there is no absolutely correct answer.
If the const
and &
get far apart, as in
krog::FlamBlott<std::map<HurkleKey,Spleen<int>>
speckleFlams( const krog::Floonage & floon, const std::map<krog::HackleSpoon,std::vector<krog::HeckleObservation<OBSN>>> & obsmap);
krog::FlamFinagleReport
finagleFlams( const krog::Floonage & floon, std::map<krog::HackleSpoon,std::vector<krog::HeckleObservation<OBSN>>> & obsmap)
... then it becomes easy to miss that the first 'obsmap' is a const reference and the second is not.
I use the T const& notation myself, and I recommend it to everyone. The reason is the ergonomics - i find it to reduce eye movement.
@grego already made a great point on how "const" being close to "&" prevents bugs. Usualy when I find "&" I want to know if it is const or not, and moving my eyes left-and-right is not what I want to do all the time.
There is another reason for <T const&> not mentioned before - code alignment. Let's see which declaration is easier to read:
void append(std::string& str,
const std::vector<std::string>& elements,
const char* delimiter);
void append(std::string& str,
std::vector<std::string> const& elements,
char const* delimiter);
<const T&> hides the type in the middle, while <T const&> exposes it on the left side. <T const&> aligns the type to the same column sliding from top to bottom can be with much less left-right eye movement when looking for a specific argument's type.
For the same reason I like the trailing return type notation (auto f(...) -> R)
精彩评论