在 lambda 中通过引用捕获的对象的生命周期

Lifetime of an object captured by reference in lambda

我有以下 C++ 代码。 Lambda 正在通过引用捕获地图对象,并且能够在该地图对象生命周期结束后访问它。

using VOID_VOID = std::function<void ()>;
using VOID_MAP = std::function<void (std::map<std::string, std::string> &)>;
using FUNC_MAP = std::function<VOID_VOID (std::map<std::string, std::string> &)>;

FUNC_MAP getLambda(VOID_MAP func)
{
    auto outer_lambda = [func](std::map<std::string, std::string> & m)->VOID_VOID {
        auto inner_lambda = [func, m]() mutable {
            m.erase("A");
            m["D"] = "4";
            func(m);
        };
        return inner_lambda;
    };
    return outer_lambda;
}

VOID_VOID test(FUNC_MAP f)
{
  std::map<std::string, std::string> m = {{"A","1"}, {"C","3"}, {"B","2"}};
  return f(m);
}

int main()
{
  auto a = [](std::map<std::string, std::string> &z){
    for(auto p:z)
      std::cout << p.first << ":" << p.second << "\n";
  };
  auto outer_lambda = getLambda(a);
  auto fut = std::async (test, outer_lambda);
  auto inner_lambda = fut.get();

  auto fut2 = std::async (inner_lambda);
  fut2.wait();
  return 0;
}

以上代码的输出是

B:2
C:3
D:4

既然地图对象 m 的生命周期是 test() 函数,那么如何仍然可以从 inner_lambda 通过引用捕获它的地方访问它?

Since the life of map object m is test()

m 的生命周期是定义它的 lambda 的生命周期(= 按值捕获它)。该 lambda 从 getLamda() 返回,并作为 main() 中的 inner_lambda 传递给 std::async()。所以,它在 fut2 未来还活着。 wait()ing 在未来执行 inner_lambda,它擦除 A 并添加 D,并产生您看到的输出。