I am reading about the new C++11 syntax for iterating over STL containers. So far I came across the following example:
std::vector<int> plus;
....
for(int l : plus)
{
std::cout << l;
}
My question is does the above syntax make a copy of the int ? If so wouldnt this be more efficient ?:
for(int& l : plus)
Semantically, it makes a copy, although for built-in types there may be no efficiency hit, in fact it may even be cheaper to use a copy. But if you have expensive to copy objects, it is a better idea to use const
references in the loop.
std::vector<ExpensiveToCopy> v;
for (const auto& i : v)
std::cout << i << std::endl;
You should only really use non-const references if you want to mutate the object.
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