如果lambda返回一个coroutine,并且这个lambda有capture,那一般会有lifetime issue。
当lambda被销毁后,它的capture list也没了。
所以当返回的coroutine被resume时候,就触发了use-after-free。
那如果使用deducing this呢?lambda本身被存储在coroutine frame上。
我试了一下,gcc用这个trick可以逃过asan的报错。
各位有什么经验?
g++-14 main.cpp -std=c++26 -Wall -Wextra -fsanitize=address
#include <coroutine>
#include <exception>
#include <cstdio>
struct MyCoroutine {
struct promise_type {
MyCoroutine get_return_object() {
return {std::coroutine_handle<promise_type>::from_promise(*this)};
}
std::suspend_always initial_suspend() { return {}; }
std::suspend_never final_suspend() noexcept { return {}; }
void return_void() {}
void unhandled_exception() {}
};
std::coroutine_handle<promise_type> handle;
};
MyCoroutine my_coroutine(int a)
{
auto lambda = [a](this auto self) -> MyCoroutine { // <---- good
// auto lambda = [a]() -> MyCoroutine { // <---- bad
std::printf("%d\n", a);
co_return;
};
return lambda();
}
int main() {
auto c = my_coroutine(12);
c.handle.resume();
return 0;
}
--
修改:allegro FROM 116.169.6.*
FROM 116.169.6.*