C++ Logo

std-proposals

Advanced search

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

From: Piotr Nycz <piotrwn1_at_[hidden]>
Date: Wed, 29 Jan 2025 18:47:11 +0100
śr., 29 sty 2025 o 17:29 <std-proposals-request_at_[hidden]> napisał(a):
>
> Send Std-Proposals mailing list submissions to
> std-proposals_at_[hidden]
>
> To subscribe or unsubscribe via the World Wide Web, visit
> https://lists.isocpp.org/mailman/listinfo.cgi/std-proposals
> > > 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.
>

Not sure if already mentioned in this thread - but the rules here are
clear - never pass temporaries by reference to any coroutine, see:

https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Rcoro-reference-parameters

"CP.53: Parameters to coroutines should not be passed by reference"

This rule says to not pass any references - but we can work around
this - if references are really necessary - by using
`std::reference_wrapper<T>` -- this reference_wrapper type cannot bind
to temporaries.

`some_type safe_coro(std::reference_wrapper<IDep1> dep1,
std::reference_wrapper<const IDep2> dep2, SomeValue value) { }`

read more here:
https://stackoverflow.com/questions/77996491/c-coroutines-and-const-reference-parameters/78021796#78021796

BR,
Piotr

Received on 2025-01-29 17:47:25