I know of the difference between auto, auto&, const auto and const auto& (for example in a “for each” loop), but one thing that surprised me is:
std::string bla;
const std::string& cf()
{
return bla;
}
int main (int argc, char *argv[])
{
auto s1=cf();
const std::string& s2=cf();
s1+="XXX"; // not an error
s2+="YYY"; //error as expected
}
So can somebody tell me when the type of x in the expression auto x = fun(); won’t be the same type as the type of the return value of the fun()?
The rules for
autoare the same as for template type deduction:In general, if you want a copy, you use
auto, and if you want a reference you useauto&&.auto&&preserves the constness of the referene and can also bind to temporaries (extending their lifetime).