Search code examples
c++c++-coroutine

Is there any guarantees on where the coroutine C++ return object is stored?


Let the following be a coroutine:

ReturnType foo(Args args)

And the following calling scenario:

void caller() {
   ReturnType ret = foo(...);
}

To my understanding after calling the coroutine foo:

  1. coroutine activation frame is constructed (::new is used if necessary)
  2. promise_type is constructed in the activation frame, let's say the following is called: promise_type promise{...};
  3. promise.get_return_object() is called.
  4. then there is a call to co_await promise.initial_suspend().
  5. Now there are two options: foo() is suspended or not

If foo is suspended, is there now a return statement to of retun_object back to caller? Possibly there is a Return Value Optimization?

If foo is not suspended, I imagine that coroutine needs to store the return_object on the coroutine activation frame, possibly on the stack or heap part of the coroutine activation frame then at first point of suspension or co_return, there is a return return_object statement that returns the object back to caller. Am I right?


Solution

  • If foo is suspended, is there now a return statement to of retun_object back to caller?

    There doesn't need to be. The call to get_return_object already filled in the caller's return value. If the coroutine needed to store the return object (or more likely, store the actual return value, with the value given to the caller pointing to it), then it has the opportunity to do so in get_return_object. That's what this function is for.

    As with any function's return value, it lives on the caller's stack, not the function itself.