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.
auto &&
always works. That's why it's "universal". If necessary, the deduced type will be qualified. – Sussnaconst auto&&
is not a forwarding reference, it's const rvalue reference – Arawnconst auto&&
is almost always wrong. – Quackerytemplate<class T> void func(T&&)
. But it seems to me that "reference collapsing rules" do apply here, still. So I assumed one can call this "universal reference", informally. Am I wrong? – Apomorphineconst
, mainly. I missed that. Of course, thank you. – Apomorphineauto&&
, with no qualifiers, is universal/forwarding reference. None of the following are universal references:const auto&&
,volatile auto&&
,const volatile auto&&
,auto*&&
, and so forth... – Arawnauto
used as a type specifier uses the same rules as template argument deduction procedure, in other wordsconst auto&& = x;
is the same astemplate<class T> void f(const T&& t); f(x);
. – ArawnT
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&&
– Arawnauto&
andauto&&
, as well asconst auto&
andconst auto&&
. they have completely different meaning. – Arawn