How to prevent unnecessary memory usage in recursive functions

I just wrote a recursive function, and it became clear to me that all the variables that I use inside the function will remain in memory until the recursion breaks. If I recurs many times or allocate large amounts of memory for variables that are not used when calling a sequential recursive function, can this lead to excessive memory usage?

eg. in the following, only vec2used in the next recursion, temp_intand temp_vecwill continue to occupy memory unnecessarily.

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);
}

Should I allocate all the memory with the new commands and delete them before calling the function? Or is there some other way to deal with this

+3
7

, . , , .

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);
}
+6

, , .

, , , . , , .

()

int foo(int i) {
  if (stop_condition(i))
    return stuff;
  // fancy computation
  return foo(bar);
}
+5

, , . , std::vector. . , , . , .

+1

- temp_vec .

temp_vec.clear();

, clear()

std::swap(temp_vec. std::vector<int>());

, temp_vec , , . . .

Btw,

int recurse(std::vector<int> arg_vec) {

, :

int recurse(const std::vector<int> &arg_vec) {
0

Tail , - (, factores) , . C ++. , . , -O2.

0

, , , . - :

void subfunction(vector arg_vec, vector result_vec)
{
   int temp_int;
   vector temp_vec;

   // do stuff
   return;
}

int recurse(vector arg_vec) {
   vector vec2;

   subfunction(arg_vec, vec2);
   recurse(vec2);
}

, , , , .

0

std::vector . - ( size_t ) - . std::vector size_t . - , , , ( , , , ).

0

Source: https://habr.com/ru/post/1762091/


All Articles