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.
The definition of auto is an abbreviation for automobile which is a machine with an engine, four wheels, and room for passengers that is used to transport people on land. A car is an example of an auto.
auto- 1. a combining form meaning “self,” “same,” “spontaneous,” used in the formation of compound words: autograph, autodidact.
Auto is a noun - Word Type.
word-forming element meaning "self, one's own, by oneself, of oneself" (and especially, from 1895, "automobile"), from Greek autos, reflexive pronoun, "self, same," which is of unknown origin.
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 rules 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&&
orconst auto&&
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With