警告 C26810

擷取變數 ' var ' 的存留期可能會在協同程式繼續時結束。

備註

警告 C26810 會在變數的存留期結束後,于繼續協同程式中結束時觸發。

程式碼分析名稱: COROUTINES_USE_AFTER_FREE_CAPTURE

範例

下列程式碼會產生 C26810。

#include <experimental/generator>
#include <future>

using namespace std::experimental;

coroutine_handle<> g_suspended_coro;

// Simple awaiter to allows to resume a suspended coroutine
struct ManualControl
{
  coroutine_handle<>& save_here;

  bool await_ready() { return false; }
  void await_suspend(coroutine_handle<> h) { save_here = h; }
  void await_resume() {}
};

void bad_lambda_example1()
{
  int x = 5;
  auto bad = [x]() -> std::future<void> {
    co_await ManualControl{g_suspended_coro};  // @expected(26810), Lifetime of capture 'x' might end by the time this coroutine is resumed.
    printf("%d\n", x);
  };
  bad();
}

若要修正此警告,請考慮使用 by-value 引數,而不是擷取:

void bad_lambda_example1()
{
  int x = 5;
  auto good = [](int x) -> std::future<void> {
    co_await ManualControl{g_suspended_coro};
    printf("%d\n", x);
  };
  good(x);
}

或者,如果協同程式保證比 Lambda 物件短,請使用 gsl::suppress 來隱藏警告,並在批註中記錄存留期合約。

另請參閱

C26811