为什么基于范围的for语句通过auto&&? [英] Why does a range-based for statement take the range by auto&&?
问题描述
基于范围的 for
语句在§6.5.4中定义为等同于:
{
auto&&& __range = range-init;
for(auto __begin = begin-expr,
__end = end-expr;
__begin!= __end;
++ __ begin){
for-range-declaration = * __ begin;
语句
}
}
其中 c>
pre>
for(for-range-declaration:expression)=> (expression)
for(for-range-declaration:braced-init-list)=> braced-init-list
(该子句进一步指定其他子表达式的含义) p>
为什么是 __ range
给定推导类型 auto&&
?我对 auto&&&
的理解是,通过传递表达式的原始价值(lvalue / rvalue)通过 std ::转发
。但是, __ range
不会通过 std :: forward
传递到任何地方。它只在获取范围迭代器时使用,例如 __ range
, __ range.begin()
或 begin(__ range)
。
使用通用参考的好处是 auto&& ;
?不会 auto&
足够了?
注意:据我所知,提案没有说明选择 auto& ;&
。
足够了?
不,不会。它不允许使用计算范围的 r值表达式。使用 auto&&&
是因为它可以绑定到l值表达式或 r值表达式。因此,您不需要将范围粘贴到变量中以使其工作。
或者,换句话说,这是不可能的: p>
for(const auto& v:std :: vector< int> {1,43,5,2,4})
{
}
c $ c> const auto& 够用吗?
不,一个 const std :: vector
只会返回 const_iterator
s到它的内容。如果你想做一个非 - const
遍历内容,这将无济于事。
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&&
.
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_iterator
s to its contents. If you want to do a non-const
traversal over the contents, that won't help.
这篇关于为什么基于范围的for语句通过auto&&?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!