[C ++ lambda函数导致内存泄漏

问题描述 投票:-1回答:1
  int AsyncUpdator::EnqueueTask(TaskInfo task_info) {
-    auto task = [=] {
-        this->DoTask(task_info);
-    };
+    auto task = std::bind(AsyncUpdator::DoTask, task_info);
    return 0;
}

    struct TaskInfo {
       GetRequest get_request; // this is a protobuffer structure
       uint64_t log_id;
   };

读取的行会引起问题,但绿线不会导致问题?

c++ memory-management memory-leaks
1个回答
1
投票

在第一个选项中,auto task = [=] () {};捕获局部变量作为副本,但std::bind捕获您的task_info作为右值引用,并使用转发将其作为参考传递给您的函数。

如果您不想使用std::bind,请切换lamba以像auto task = [&] () {};一样通过引用进行捕获。

© www.soinside.com 2019 - 2024. All rights reserved.