简体   繁体   English

Foreach 循环比传统的 for 循环使用更多的堆栈内存?

[英]Foreach loop uses more stack memory than traditional for loop?

In one of my programs I was using a for each loop that looked similar to this在我的一个程序中,我使用了一个与此类似的 for each 循环

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:并且 Visual Studio 抱怨这会导致函数使用比最大值更多的堆栈内存,因此我将循环更改为:

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?这是因为 for each 循环生成循环中对象当前迭代的引用/副本吗? 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编辑:如果改变了任何东西, components是一个std::vector

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.如果由于错误,循环尝试修改容器中的值,您的 C++ 编译器会很有帮助地抱怨。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM