警告 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();
}
若要修复此警告,请考虑使用按值参数而不是捕获:
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
禁止显示警告并在注释中记录生存期协定。
另请参阅
反馈
https://aka.ms/ContentUserFeedback。
即将发布:在整个 2024 年,我们将逐步淘汰作为内容反馈机制的“GitHub 问题”,并将其取代为新的反馈系统。 有关详细信息,请参阅:提交和查看相关反馈