Why do some people prefer “T const&” over “const T&”?

后端 未结 9 1518
醉梦人生
醉梦人生 2020-12-02 12:25

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 constan

相关标签:
9条回答
  • 2020-12-02 12:51

    That's because some find it helpful to read the declaration right-to-left.

    char const*
    const char*
    

    are both pointer to const char.

    0 讨论(0)
  • 2020-12-02 12:51

    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.

    0 讨论(0)
  • 2020-12-02 12:52

    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.

    0 讨论(0)
提交回复
热议问题