C++ Logo

std-proposals

Advanced search

Re: [std-proposals] std::generator initial_suspend dropping all temporaries out of scope

From: Arthur O'Dwyer <arthur.j.odwyer_at_[hidden]>
Date: Tue, 28 Jan 2025 15:45:12 -0500
On Tue, Jan 28, 2025 at 1:43 PM Karl Semich via Std-Proposals <
std-proposals_at_[hidden]> wrote:

> Hi!
>
> I'm trying out c++23 std::generator and noticing that I cannot safely pass
> arguments to my generators that are temporaries such as
> std::initializer_list. It seems like this is because promise_type's
> initial_suspend returns suspend_always, so passed temporaries are out of
> scope as soon as initial code is executed.
>
> Where can I read about this and best practices, or is it a mistake? It
> looks like a mistake to me.
>

It's certainly been known in some circles since forever. Here's a blog post
I wrote on the subject in July 2019. Actually the *subject* of the blog
post was an exciting new *cutting-edge* way to dangle a reference that I'd
just learned; the way you're talking about here is what I called the
"boring old way" back in 2019.
https://quuxplusone.github.io/blog/2019/07/10/ways-to-get-dangling-references-with-coroutines/

My understanding is that if initial_suspend returned suspend_never, then
> the developer could accept temporaries and copy their contents to the stack
> in the initial code block of the generator. But as it is, there can be
> surprising subtle memory access errors in code not aware of the limitation
> that generators cannot safely accept temporaries at all.
>
> Ideally there would be some way to configure this.
>

I believe there is: it's "write your own generator type instead of using
the one we standardized." Coroutines in C++ is a really low-level,
not-for-ordinary-programmers kind of feature. It's probably not possible to
"just use" coroutines in C++ in the way you can in, say, Python.

–Arthur

Received on 2025-01-28 20:45:25