在while循环中调用函数()是否在每次循环迭代时使用内存
Does a function() call in a while loop uses memory everytime the loop iterate?
我是新来的,我目前正在学习如何用c++编程。
所以我的问题是:每次循环迭代时,while循环内的函数调用是否都会消耗内存?
的例子:
int count = 0;
while (count < 10)
{
function_call(); // Will this consume 10x more memory?
++count;
}
No。__
你调用你的函数10次,所以你的函数使用的内存被使用了10次。但是这个函数只有在执行结束后才会被再次调用,所以无论它使用了什么资源都已经被释放了。
所以最后,它使用了相同数量的内存,只是保存时间延长了10倍。
†:这是假设你的函数没有泄漏内存。
任何未释放的手工分配的内存都将被使用。如果你的函数泄漏了N个字节,那么这个循环将泄漏10乘以N个字节。但希望你没有泄露任何信息。;)
这个问题是模棱两可的,因为c++有两种类型的内存,动态和自动(通常称为堆和堆栈),它们具有不同的特征。
int count = 0;
while (count < 10) {
function_call(); // Will this consume 10x more memory?
++count;
}
1)这会消耗10倍多的自动内存吗?
答案是否定的。自动内存在范围进入时分配,并在范围退出时释放。对function_call()的循环重复调用将每次调用都"重新开始"。
2)这会消耗10倍多的动态内存吗?
答案-不知道你提供的。
如果function_call()不使用动态内存
NO - a) if function_call()"使用"有限的动态内存通过new(), and获得B)在返回之前使用delete释放所有的动态内存。
NO - a)如果function_call '使用'获得的有限动态内存使用new(),和B)一个different_function_call适当地释放内存。
Research term for you: object lifetime. Some dynamic memory
needs to exists longer than the lifetime of the function_call.
Several other answers mentioned 'memory leaking'. I consider this a
coding error, and thus not relevant to your question.
Yes - a)如果function_call '使用'获得的有限动态内存使用new(),和B)没有其他代码发布它,并且C)包含function_call的进程不终止。
On most OS's, terminating the process in which this code runs will
cause the release of all dynamic memory (and other resource) back
to the OS's control, and no longer accessible to the terminated
process (or any other process in the form created).
If it is possible that this process can run until dynamic memory is
exhausted, I think what happens next is UB (undefined behavior).
相关文章:
- 基于范围的 for 循环:迭代使用一个元素扩展的向量
- 使用基于范围的循环迭代矢量时出现问题
- C++:返回一个基于范围 for 循环迭代器,其中包含继承对象
- 在分配和发布递增循环迭代器时C++无限循环(gcc 错误?
- 如何基于循环迭代器选择函数
- 如何使用基于范围的for循环迭代Rapidjson文档(它本身就是一个JSON数组)
- 在循环迭代期间将引用保存到矢量中的空指针
- 在每次循环迭代时停止代码执行毫秒
- 优先级队列(使用 pairs<int,int> ) 根据 for 循环迭代器的顶级元素
- 如何在每次循环迭代期间生成向量,存储数据,然后删除该向量?
- 先前循环迭代对当前迭代执行时间的影响
- C++使用 for 循环迭代 2 个向量
- 为什么循环迭代不打印任何东西?
- 每次循环迭代后递减迭代器都会显示出奇怪的行为
- 虽然循环迭代了C++中的太多元素
- 循环迭代后,C 函数调用不会再次调用
- 指向向量和向量的指针中的循环迭代
- 为矩阵创建动态数组,以循环迭代器命名
- for 循环 - 迭代特定元素
- 通过线程分发循环迭代