In one of my programs I was using a for each loop that looked similar to this
for(auto component : components) {
doSomethingWithComponent(component);
}
and visual studio complained that this would cause the function to use more stack memory than the maximum, so I changed the loop to:
for(int i = 0;i<components.size();i ) {
doSomethingWithComponent(components[i]);
}
and the warning went away. Is this because a for each loop generates a reference/copy of the current iteration of object in the loop? But if that is the case, I don't think that a single struct with a few integers would consume that much memory? Is there a reason for this to occur?
EDIT:
components
is an std::vector
if that changes anything
CodePudding user response:
for(auto component : components) {
This is equivalent to having
auto component=components[i];
being performed on each iteration of the loop. A (mostly useless) copy is made of each value in the container, on each iteration of the loop. Hence the stack usage.
This is avoided simply by using a reference:
for(auto &component : components) {
Even better, if the loop is not supposed to modify the contents of the container:
for(const auto &component : components) {
And your C compiler will helpfully complain if, due to a bug, the loop attempts to modify the value in the container.