title: recursive algorithm and memory management in C++
body: <p>I'm using <code>boost::filesystem</code> and a custom recursive algorithm to iterate through image files in a directory. The algorithm will read adjacent image contents to two <code>cv::Mat</code>, add them together, write them to a temporary file and then recursively proceed with all temporaries as many times as necessary until one sole image is generated. The client code looks like this:</p>
  
  <pre><code>  auto result = my_recursive_algorithm(boost::filesystem::directory_iterator{path_to_folder},
                       boost::filesystem::directory_iterator{}, [](auto file_a, auto file_b){
                         cv::Mat image_a{cv::imread(file_a.path().string())}; 
                         cv::Mat image_b{cv::imread(file_b.path().string())};
                         cv::Mat sum {};
                         cv::addWeighted(image_a,0.5,image_b,0.5, 0, sum);
                         // generate a unique new_path
                         cv::imwrite(new_path, sum);
                         return new_path;
                       });
  </code></pre>
  
  <p>I am taking this approach because I have no guarantees of the number of images my program will have to process. It could be that they are too many to fit in memory. I am wandering, however, if this a safe approach. What happens when the lambda returns? Since I'm only returning <code>new_path</code> I'd expect all the destructors of all other local variables (the <code>cv::Mat</code>) to be called when each individual lambda call finishes, right? Or could it be that they will be only called once the whole recursive call is done? In the latter case my approach would be equivalent to loading everything in memory in the first place.</p>