Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

for loop syntax with containers - Is a copy made?

Tags:

c++

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)
like image 998
Rajeshwar Avatar asked Dec 07 '22 04:12

Rajeshwar


1 Answers

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.

like image 133
juanchopanza Avatar answered Dec 26 '22 20:12

juanchopanza