| title | Warning C26811 | ||
|---|---|---|---|
| description | Learn more about: Warning C26811. | ||
| ms.date | 05/11/2023 | ||
| f1_keywords |
|
||
| helpviewer_keywords |
|
Lifetime of the memory referenced by parameter 'var' might end by the time the coroutine is resumed.
Warning C26811 is triggered when a variable might be used after its lifetime ended in a resumed coroutine.
Code analysis name: COROUTINES_USE_AFTER_FREE_PARAM
The following code generates C26811.
#include <experimental/generator>
#include <future>
using namespace std::experimental;
// 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() {}
};
coroutine_handle<> g_suspended_coro;
std::future<void> async_coro(int &a)
{
co_await ManualControl{g_suspended_coro}; // @expected(26811), Lifetime of 'a' might end by the time this coroutine is resumed.
++a;
}To fix this warning, consider taking the argument by value:
std::future<void> async_coro(int a)
{
co_await ManualControl{g_suspended_coro};
++a;
}Alternatively, when the lifetime of a is guaranteed to outlive the lifetime of the coroutine, suppress the warning using gsl::suppress and document the lifetime contracts of the code.