什么是`auto&&在基于范围的for循环中做? [英] What does `auto && e` do in range-based for-loops?
问题描述
假设我使用基于范围的循环进行编程时的当前规则为
使用
e:...)或
。for(auto& e:...)
a:...)
我根据自己的经验和此问题。
但在阅读了新的循环循环我不知道,我不应该用 所以,我问自己,如果我的新规则是 使用 或者这不总是工作,因此应该是相当复杂的 检查 何时以及是否应该使用 这留下了&&
替换我的规则中的&
?如这里所示,这看起来像
替换(auto const& e:...)
或 for(auto& e:...)
如果可能...
const& e:...)
或为(auto& e:...)
for(auto const& e:...)
或 for(auto& e:...)
auto&&&&&
已在 Howard Hinnant 这里。
x
在
auto&& x = ... expr ...
实际上是。它被处理为好像有一个函数模板定义
template< class U> void f(const U& u);
,并且 x
的类型与 u
[§7.1.6.4。(7)]相同。
这意味着非作为RValue参考,但作为通用/转发参考 - 参考折叠规则。
这也适用于
const auto&& x = ... expr ...
§7.1.6.4。(7)中的示例指出,至少对于 const auto& x
。
但是,如PiotrS在问题评论中所说,任何限定词都会废除URef值:
否,因为
T
在模板< class T& void f(const T&&)
是转发引用,const auto&&
在参数声明中发生T&&
的事实并不意味着它是转发引用。只有不含const
或volatile $ c $的限定词的纯粹
T& c>是转发引用,意味着它必须
template< class T> void f(T&&)
或auto&&&
,永远不要const T&& c $ c> or const
auto&&&< / code>
Assuming my current rule when programming with range-based loops says
Use
for(auto const &e :...)
orfor(auto &e:...)
when possible overfor(auto a: ...)
.
I base this on my own experience and this question for example.
But after reading about the new terse for loops I wonder, should I not replace my &
in my rule with &&
? As written here this looks like the Meyers' Universal References.
So, I ask myself, should my new rule either be
Use
for(auto const &&e :...)
orfor(auto &&e:...)
when possible ...
or does that not always work and therefore should rather be the quite complicated one
Check if
for(auto const &&e :...)
orfor(auto &&e:...)
is possible, then considerfor(auto const &e :...)
orfor(auto &e:...)
, and only when needed do not use references.
When and if you should use auto&&
in for loops has been explained very nicely by Howard Hinnant here.
This leaves the question what x
in
auto &&x = ...expr...
actually is. And it is handled as if there there were a function template definition
template <class U> void f(const U& u);
and the type of x
is deduced by the same tules as u
[§7.1.6.4.(7)].
This means it is not handled as a RValue Reference, but as a "Universal/Forwarding Reference" -- the "Reference Collapsing Rules" apply.
This also holds for
const auto &&x = ...expr...
as the example in §7.1.6.4.(7) states, at least for const auto &x
.
But, as PiotrS says in the questions comments, any qualifiers nullifies the URef-ness:
no, because neither
T
intemplate<class T> void f(const T&&)
is a forwarding reference, norconst auto&&
is. The fact thatT&&
occurs in parameter declaration does not imply it is forwarding reference. Only pureT&&
with no qualifiers likeconst
orvolatile
is forwarding reference, meaning it has to betemplate<class T> void f(T&&)
orauto&&
, and neverconst T&&
or constauto&&
这篇关于什么是`auto&&在基于范围的for循环中做?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!