Why does a range-based for statement take the range by auto&&?

前端 未结 1 1144
离开以前
离开以前 2020-12-31 03:28

A range-based for statement is defined in §6.5.4 to be equivalent to:

{
  auto && __range = range-init;
  for ( auto __begin =          


        
1条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-31 04:05

    Wouldn't auto& suffice?

    No, it wouldn't. It wouldn't allow the use of an r-value expression that computes a range. auto&& is used because it can bind to an l-value expression or an r-value expression. So you don't need to stick the range into a variable to make it work.

    Or, to put it another way, this wouldn't be possible:

    for(const auto &v : std::vector{1, 43, 5, 2, 4})
    {
    }
    

    Wouldn't const auto& suffice?

    No, it wouldn't. A const std::vector will only ever return const_iterators to its contents. If you want to do a non-const traversal over the contents, that won't help.

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