zen*_*nna 5 c++ memory recursion memory-management
我刚刚编写了一个递归函数,我意识到我在函数中使用的所有变量都将保留在内存中,直到递归中断为止.如果我正在递归很多次或为后续递归函数调用中未使用的变量分配大量内存,这是否会导致大量浪费内存使用?
例如,在下面的例子中,仅vec2用于以下的递归,temp_int并且temp_vec将不必要地继续占用记忆.
int recurse(std::vector<int> arg_vec) {
int temp_int i;
std::vector<int> temp_vec;
std::vector<int> vec2;
//... do some processing with arg_vec and temp_vec and result is stored in vec2
recurse(vec2)
return if (some condition met);
}
Run Code Online (Sandbox Code Playgroud)
那么我应该使用新命令分配所有内存并在函数调用之前删除它们吗?或者是否有其他方法来处理这个问题
您可以使用范围大括号指定范围.范围中声明的任何内容都会在范围的末尾被销毁.
int recurse(std::vector<int> arg_vec) {
int temp_int i;
std::vector<int> vec2;
{
std::vector<int> temp_vec;
//... do some processing with arg_vec and temp_vec and result is stored in vec2
} // temp_vec is destructed here. vec2 is not because it is outside this scope.
recurse(ec2)
return if (some condition met);
}
Run Code Online (Sandbox Code Playgroud)
通常,在这种情况下您所做的是尾递归,它允许编译器优化它.
这意味着,递归函数最后做的就是调用自身.如果您有进一步的说明,我不知道优化有多好.
编辑(澄清)
int foo(int i) {
if (stop_condition(i))
return stuff;
// fancy computation
return foo(bar);
}
Run Code Online (Sandbox Code Playgroud)