3 ms·
Huh, I always thought that there is an optimization to always choose the most consty and referency option possible. So if you write `auto` but don't modify the
by captainmuon 10y ago
Huh, I always thought that there is an optimization to always choose the most consty and referency option possible. So if you write `auto` but don't modify the item in the loop, it may choose to use a reference / pointer under the hood, as if you wrote `auto &` or `const auto &`. But it can't strip away the `&`.
The reason is that I imagined C++ can substitute anything for auto, so it can make `auto` into a pointer to Foo, but it can't turn `auto &` into `Foo`. (In a first pass, of course due to the as-if rule the compiler can do whatever it wants when you are not looking.)
In the example the author reccommends against, `for (const auto x : range)`, I would think it means:
- const: don't let me modify x (enforce const-correctness at compile time)
- Make a copy or reference, whatever is faster.
Particularly, I think/thought: `const` does not tell the compiler to make a copy. The lack of `&` allows the compiler to make a copy.
I'm sure this interpretation is not 100% what's in the standard, but a intuition I developed from observation, so probably some of it is wrong.
- revelation 10y agoauto doesn't mean "make a copy or reference, whatever is faster". auto first and foremost means "make a copy". Then sometimes compilers can do a trick called copy-elision and you might be working on a reference. But generally assume it's going to be a copy. auto& means only make a reference.