移动会跟踪引用吗?

Will moving keep track of references?

我想知道下面的代码是否可以安全使用,如果不安全,是否可以使其安全?

{
    ThreadState state = ThreadState::Running;
    auto pair = std::make_pair(std::async([&state] ()
    {
        state = ThreadState::Waiting;
    }), std::move(state));
    someVector.emplace(std::move(pair));
}

lambda 会在执行 std::move 后跟踪正确的引用吗?状态的寿命会延长吗?我可以改进它以创建一对 lambda 及其捕获状态吗?

Will the lambda keep track of the proper reference after performing std::move?

不,lambda 将引用移出的 state,它现在将具有不确定的值。

Will the lifetime of the state be extended?

state 的生命周期在封闭范围结束时结束。 std::pair 中状态的生命周期,您将 state 的值移动到其中,当然将由您 emplace/push 进入的 std::vector 的生命周期决定。

Can I improve this to create a pair of a lambda and its captured state?

一种解决方案,虽然它使用动态存储,但使用 std::unique_ptr:

{
  auto state = std::make_unique<ThreadState>(ThreadState::Running);
  vec.emplace_back(
    std::async([s = state.get()] ()
    {
        *s = ThreadState::Waiting;
    }),
    std::move(state)
  );
}