C++ Logo

std-proposals

Advanced search

Re: [std-proposals] return value lives until end of scope

From: Andrey Semashev <andrey.semashev_at_[hidden]>
Date: Sat, 23 May 2026 14:12:45 +0300
On 23 May 2026 10:36, Frederick Virchanza Gotham via Std-Proposals wrote:
> On Thursday, May 21, 2026, Jonathan Wakely wrote:
>
> Yeah, I don't want spooky changes to the lifetime model and how it
> interacts with scopes to happen implicitly based on something far
> away on the function declaration. If somebody adds __persistent to a
> declaration, it silently changes the meaning of existing callers. No
> thanks.
>
> What if we were to move the 'mark' to the calling site. Perhaps a unary
> operator? So the following:
>
> int main(void)
> {
> %async(Func);
> }
>
> would be the same as:
>
> int main(void)
> {
> auto dummy = async(Func);
> }

While I do not like the unary % idea (because all of the implicitness
and ambiguity with loops, and because it doesn't actually solve the
originally stated problem with std::async), I think there are cases
where one would want to declare a variable in an outer scope, where the
`auto _` approach doesn't quite work. The following pattern comes up
quite often:

  type var = ???;
  if (condition1)
  {
    auto inner_var = do_bunch_of_stuff();
    if (condition2(inner_var))
      var = compute_var();
  }

  use_var(var);

Here, `type` may not always be possible to shortcut as `auto`, if the
initializer is not easy to produce. So one has to spell out the type
explicitly.

The other problem is, obviously, var's initializer and handling the case
of var being not initialized in the nested scope. You would typically
use a sentinel value for the initial initializer or std::optional, but
the former is not always possible and the latter requires an include and
has runtime overhead.

I'm not necessarily proposing a solution, but just stating that there is
a use case for out-of-scope variable declaration that could benefit from
core language support.

Received on 2026-05-23 11:12:51