我刚刚编写了一个递归函数,我突然意识到我在函数中使用的所有变量都将保留在内存中,直到递归中断。如果我递归多次或为后续递归函数调用中未使用的变量分配大量内存,这是否会导致大量内存使用浪费?
例如下面的recurse中只用到了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);
}
然后我应该使用新命令分配所有内存并在函数调用之前删除它们吗?还是有其他方法可以解决这个问题
请您参考如下方法:
您可以使用范围大括号来指定范围。范围内声明的任何内容都会在范围末尾销毁。
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);
}