什么是`auto&&在基于范围的for循环中做? [英] What does `auto && e` do in range-based for-loops?

查看:143
本文介绍了什么是`auto&&在基于范围的for循环中做?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我使用基于范围的循环进行编程时的当前规则为


使用 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 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 :...) or for(auto &e:...) when possible over for(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 :...) or for(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 :...) or for(auto &&e:...) is possible, then consider for(auto const &e :...) or for(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 in template<class T> void f(const T&&) is a forwarding reference, nor const auto&& is. The fact that T&& occurs in parameter declaration does not imply it is forwarding reference. Only pure T&& with no qualifiers like const or volatile is forwarding reference, meaning it has to be template<class T> void f(T&&) or auto&&, and never const T&& or const auto&&

这篇关于什么是`auto&amp;&amp;在基于范围的for循环中做?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆