c++20和23都没问题
deducing this反而不行
【 在 allegro 的大作中提到: 】
: 标  题: deducing this是lambda coroutine lifetime issue的解决方法吗
: 发信站: 水木社区 (Mon Apr 28 13:00:09 2025), 站内
: 
: 如果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;
: }
:: 
: --
: WEEP NOT FOR ROADS UNTRAVELED
: ※ 修改:·allegro 于 Apr 28 13:03:55 2025 修改本文·[FROM: 116.169.6.*]
: ※ 来源:·水木社区 
http://www.mysmth.net·[FROM: 116.169.6.*]
--
修改:allegro FROM 116.169.6.*
FROM 117.129.54.*