Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
218 views
in Technique[技术] by (71.8m points)

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

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

{
  auto && __range = range-init;
  for ( auto __begin = begin-expr,
             __end = end-expr;
        __begin != __end;
        ++__begin ) {
    for-range-declaration = *__begin;
    statement
  }
}

where range-init is defined for the two forms of range-based for as:

for ( for-range-declaration : expression )         =>   ( expression )
for ( for-range-declaration : braced-init-list )   =>   braced-init-list

(the clause further specifies the meaning of the other sub-expressions)

Why is __range given the deduced type auto&&? My understanding of auto&& is that it's useful for preserving the original valueness (lvalue/rvalue) of an expression by passing it through std::forward. However, __range isn't passed anywhere through std::forward. It's only used when getting the range iterators, as one of __range, __range.begin(), or begin(__range).

What's the benefit here of using the "universal reference" auto&&? Wouldn't auto& suffice?

Note: As far as I can tell, the proposal doesn't say anything about the choice of auto&&.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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<int>{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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...