Maxxx
1
I have some code
for (auto &touch : touches)
{
auto start = touch->getStartLocation();
}
where touches is
const std::vector<Touch*> &touches
All is well with the world.
But I accidentally missed off the &, so had
for (auto touch : touches)
{
auto start = touch->getStartLocation();
}
and everything still works.
Can someone explain to a noob like me , why is the & ‘optional’ in this case?
(I have tried a few variations, and it seems to me it is always optional?)
The & mean in c++ address of
As you see the Touch is pointer *
I think the auto keyword, taking the care in that case… Maybe
It isn’t really optional.
for (auto touch : touches) creates copies of the pointers.
for (auto & touch : touches) doesn’t.
Actually it is recommended to always write
for (auto && element : range)
(with 2 &) when doing range-based loops.
It has something to do with “reference collapsing” and “universal references”… Never mind, just do it…
More information here: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n3853.htm
and here: https://isocpp.org/blog/2012/11/universal-references-in-c11-scott-meyers