简体   繁体   English

lambda c++ 的生命周期

[英]Lifetime of lambda c++

I have the following situations and trying to understand the scope of the lambdas我有以下情况并试图了解 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.所以我们用它的主要 lambda 函数启动一个线程。 I am guessing the std::async will take care of the scope of that main lambda function.我猜std::async将负责该主要 lambda 函数的范围。 However, in my application I also invoke a function within the main lambda.但是,在我的应用程序中,我还在主 lambda 中调用了一个函数。 That function also requires a lambda.该函数还需要一个 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.我的问题是嵌套的 lambda 是否实际上具有本地范围,因此可能导致未定义的行为,或者我是否错过了使其工作的东西。

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) .在 future 之前创建 dbserver 并让 future 在 dbserver 之前超出范围就可以了(future 析构函数将与线程结束同步)。 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.如果您以某种方式无法管理,您可能需要使用std::shared_ptr<Someclass>并将其按值传递给您的 lambda 以将数据库的生命周期延长到线程的生命周期。 (I usually am careful about using std::shared_ptr but I find this is a very good use for it) (我通常对使用 std::shared_ptr 很小心,但我发现这是一个很好的用途)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM