Does C++ range-based `for` make copies?

67 views Asked by At

I studying C++ and I am trying to understand range-based for loops. Consider the following code

std::array<int,5> items{1,2,3,4,5};

for(int item: items){
   std::cout << std::setw(10) << item;
}
std::cout << std::endl;

for(int item: items){
   item++;
   std::cout << std::setw(10) << item;
}
std::cout << std::endl;

for(int item: items){
    std::cout << std::setw(10) << item;
}
std::cout << std::endl;

It prints

1 2 3 4 5
2 3 4 5 6
1 2 3 4 5

Thus, I understand that item takes the value of the corresponding element. This makes me wonder what happens with more complicated types. My guess is that itemis a local variable that takes a copy of the corresponding element in items. Does that mean that if items is an array of larger objects, say

std::array<MyObject,5> items

the for loop takes a copy of each element?

(p.s., I know that I can change the value of the original item using int& item: items).

1

There are 1 answers

0
Serve Laurijssen On BEST ANSWER

By default it copies the elements. But when taking a reference to the items you get, well, a reference and the values will be changed.

for(int &item: items){
   item++;
}

When using objects you avoid calling the copy constructor this way.

Copy constructor called.

for (Object item: items) { }

No copy constructor called

for (Object &item: items) { }

When you need the performance of no copy constructor calling but you dont want to change the objects, make them const.

for (const Object &item: items) { }