r/cpp • u/rhidian-12_ Coroutines4Life • Feb 21 '26
Implementing your own asynchronous runtime for C++ coroutines
Hi all! Last time I wrote a blog post about writing your own C++ coroutines. Now, I wanted to highlight how to write your own C++ asynchronous runtime for your coroutines.
https://rhidian-server.com/how-to-create-your-own-asynchronous-runtime-in-c/
Thanks for reading, and let me know if you have any comments!
42
Upvotes
View all comments
Show parent comment
1
u/38thTimesACharm Feb 21 '26 edited Feb 22 '26
Isn't it okay if you pass
thisby value in C++23? Then the lambda closure object is copied into the coroutine frame where the compiler can preserve it across suspension.I've been using this on a project for a month now, and the sanitizer hasn't gone off yet. It's just two keywords, uses a big C++23 feature people will need to learn anyway, and can be enforced with a clang-tidy pass, so it seems worth it to recover the massive convenience of lambdas. But it contradicts a million guides and FAQs saying never to use coroutine lambdas, so I'd like some reassurance this is actually safe.
For C++20, I think you can also use lambda captures if you
co_awaitthe coroutine in the same line. But don't quote me on that one, and maybe that's too risky even if correct.Regarding your second point,
Obviously if you pass a reference to an object, it needs to to outlive the task that uses it. I'm more concerned about temporaries. Consider:
This seems okay because we
co_awaitthe task whilemy_stringis still alive. However, someone could very easily change it to this:This is UB, because the lifetime of the temporary
is only extended toonly lives until the first suspension point (EDIT - usually this means initial_suspend, before any of your functions body executes). So passing references seems risky, since people are accustomed to temporariesbeing extendedliving long enough in synchronous code. Is there anything I could be doing here to make the behavior safer?