What are common pitfalls when using coroutines?
Short answer
Pitfalls include dangling references: a coroutine that captures or references locals/parameters by reference can access them after the caller's frame is gone across a suspension; passing parameters by reference to a coroutine that outlives them is dangerous.
Advertisement
AModel answer
Pitfalls include dangling references: a coroutine that captures or references locals/parameters by reference can access them after the caller's frame is gone across a suspension; passing parameters by reference to a coroutine that outlives them is dangerous. Also, forgetting to keep the coroutine handle alive, or awaiting objects that don't outlive the suspension, cause use-after-free. Prefer passing owned/by-value data into coroutines.
// dangerous: reference parameter may dangle after suspension
Task process(const std::string& ref); // prefer by value/owningReal-world example
A coroutine referencing a temporary argument crashes after suspension; passing by value fixes it.
Likely follow-ups
- Why can coroutine reference parameters dangle? | How do you avoid it?
Related topics