On cppreference (which I understand is not the c++ standard itself) I have read that the coroutine state contains "local variables and temporaries whose lifetime spans the current suspension point.", (emphasis mine) but I don't think I understand how this works.

Suppose I have a coroutine that looks something like this:

/*...*/ SomeCoroutine() { const auto& ref = std::string("abc"); co_yield ref.size(); // assume the coroutine really does suspend co_return ref.size(); }

Before the coroutine is suspended, is ref a local variable on the stack, or is it really a member of the coroutine state (in which case I doubt it can actually be a reference)?

After the coroutine is resumed, is ref a local variable on the stack, or is it really a member of the coroutine state? If it is still a reference, is it dangling now, or did the string get copied somehow?

I think my mistake is presuming that ref is an object. ref is an alias for the materialized temporary, and its the temporary that is an object. It would make sense to me if the temporary itself is in the coroutine state all along.

wohlstad's user avatar

wohlstad

36.6k18 gold badges79 silver badges113 bronze badges

Baha's user avatar

New contributor

Baha is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.

1

From the page you quoted on cppreference.com:

Each coroutine is associated with

...

the coroutine state, which is internal, dynamically-allocated storage (unless the allocation is optimized out), object that contains

...

local variables and temporaries whose lifetime spans the current suspension point.

(emphasis is mine)

In the "normal" (non-coroutine) case the following code:

const auto& ref = std::string("abc");

Will extend the life of the temporary because of the bounding to the const-ref. This seems like exactly the case mentioned above (with my emphasis in bold).

Therefore there is no dangling reference in your code:
The std::string temporary object will be kept as a part of the coroutine state and the reference will refer to it.
Just to make it clear: as you suggested, the reference itself is not an object, but an alias to the temporary object.

wohlstad's user avatar

1 Comment

My faulty line of reasoning was something like "ref itself is an object" (incorrect) -> "ref itself is saved to / part of the coroutine state" -> "the coroutine state has the moral equivalent of a const std::string& ref member that the temporary binds to". The alternative of "the coroutine state has the moral equivalent of a std::string __tmp1 member instead and ref never occupies memory anywhere" makes a lot more sense.

2026-01-01T12:40:25.137Z+00:00

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.