問題描述
假設我在使用基于范圍的循環編程時的當前規則說
Assuming my current rule when programming with range-based loops says
盡可能使用 for(auto const &e :...)
或 for(auto &e:...)
而不是 for(自動 a: ...)
.
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.
但是在閱讀了新的 簡潔的循環 我想知道,我不應該用 &&
替換我的規則中的 &
嗎?正如此處所寫,這看起來像Meyers 的通用參考文獻.
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
盡可能使用 for(auto const &&e :...)
或 for(auto &&e:...)
...
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
檢查 for(auto const &&e:...)
或 for(auto &&e:...)
是否可行,然后考慮 for(auto const &e :...)
或 for(auto &e:...)
,并且僅在需要時才使用引用.
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.
推薦答案
Howard Hinnant 此處.
When and if you should use auto&&
in for loops has been explained very nicely by Howard Hinnant here.
這就留下了x
在
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);
并且x
的類型是按照與u
[§7.1.6.4.(7)]相同的規則推導出來的.
and the type of x
is deduced by the same rules as u
[§7.1.6.4.(7)].
這意味著它不作為 RValue 參考處理,而是作為通用/轉發參考"處理.--參考折疊規則"申請.
This means it is not handled as a RValue Reference, but as a "Universal/Forwarding Reference" -- the "Reference Collapsing Rules" apply.
這也適用于
const auto &&x = ...expr...
作為 §7.1.6.4.(7) 中的例子,至少對于 const auto &x
.
as the example in §7.1.6.4.(7) states, at least for const auto &x
.
但是,正如 PiotrS 在問題評論中所說,任何限定詞都會使 URef-ness 無效:
But, as PiotrS says in the questions comments, any qualifiers nullifies the URef-ness:
不,因為template
是轉發引用,T
都沒有.void f(const T&&)const auto&&
也不是.T&&
出現在參數聲明中的事實并不意味著它是轉發引用.只有沒有像 const
或 volatile
這樣的限定符的純 T&&
是轉發引用,這意味著它必須是 template
或 auto&&
,從不const T&&
或 const auto&&
代碼>
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&&
orconst auto&&
這篇關于什么是`auto &&e` 在基于范圍的 for 循環中做什么?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!