Redaguoti

Bendrinti naudojant


Warning C26810

Lifetime of captured variable 'var' might end by the time the coroutine is resumed.

Remarks

Warning C26810 is triggered when a variable might be used after its lifetime ended in a resumed coroutine.

Code analysis name: COROUTINES_USE_AFTER_FREE_CAPTURE

Example

The following code generates 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();
}

To fix this warning, consider using by-value arguments instead of captures:

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);
}

Alternatively, if the coroutine is guaranteed to live shorter than the lambda object, use gsl::suppress to suppress the warning and document the lifetime contracts in a comment.

See also

C26811