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

后端 未结 9 1601
醉梦人生
醉梦人生 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

    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.

提交回复
热议问题