为什么基于范围的 for 语句会通过 auto&& 获取范围? [英] Why does a range-based for statement take the range by auto&&?
问题描述
基于范围的for
语句在§6.5.4中定义为等价于:
<代码>{汽车&&__range = 范围初始化;for ( auto __begin = begin-expr,__end = 结束表达式;__开始!= __结束;++__开始) {for-range-declaration = *__begin;陈述}}
其中 range-init
是为基于范围的 for
的两种形式定义的:
for ( for-range-declaration : expression ) =>( 表达 )for ( for-range-declaration :braced-init-list ) =>花括号初始化列表
(该子句进一步规定了其他子表达式的含义)
为什么 __range
给定推导类型 auto&&
?我对 auto&&
的理解是,通过 std::forward
传递表达式,它对于保留表达式的原始值(左值/右值)很有用.但是,__range
不会通过 std::forward
传递到任何地方.它仅在获取范围迭代器时使用,作为 __range
、__range.begin()
或 begin(__range)
之一.
使用通用参考"auto&&
有什么好处?auto&
还不够吗?
注意:据我所知,提案 没有说明 auto&&
的选择.
不会自动&够了吗?
不,不会.它不允许使用计算范围的 r 值表达式.使用 auto&&
是因为它可以绑定到左值表达式 或 右值表达式.因此,您无需将范围粘贴到变量中即可使其工作.
或者,换句话说,这是不可能的:
for(const auto &v : std::vector{1, 43, 5, 2, 4}){}
<块引用>
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屋!