Home > Software design >  Lifetime of lambda c
Lifetime of lambda c

Time:07-09

I have the following situations and trying to understand the scope of the lambdas

 std::future<void> thread_run;
 void run(Someclass& dbserver){
     thread_run = std::async(std::launch::async, [&]{ 
                      dbserver.m_com.run([&dbserver]() { 
                         // implement another nested lambda for the m_com.run method. Does this get destroyed when the main thread leaves the run method. 
                      }
                  }
 }

  class dbserver{ 
     Com m_com;
   }

  class Com{
     template<typename F>
     void run(F&& func){ // do some stuff here}
  
   }

So we launch a thread with its main lambda function. I am guessing the std::async will take care of the scope of that main lambda function. However, in my application I also invoke a function within the main lambda. That function also requires a lambda.

My question is whether the nested lambda actually has a local scope and therefore could be leading to undefined behaviour or did I miss something that will make it work.

CodePudding user response:

Create the dbserver before the future and let the future go out of scope before dbserver and you are fine (the future destructor will synchronize with the end of the thread) . If you somehow cannot manage that you may need to use a std::shared_ptr<Someclass> and pass that by value to your lambda to extend the lifetime of the database to that of the thread. (I usually am careful about using std::shared_ptr but I find this is a very good use for it)

  • Related