Link capture temporary closure lifetime stored in class

Consider the following code snippet:

struct foo { };

template <typename F>
struct impl : F
{
    impl(F&& f) : F{std::move(f)} { }
    auto get() { return (*this)(); }
};

template <typename X>
auto returner(X&& x)
{
    return impl{[&x]{ return x; }};
//               ^~
}

int main()
{
    auto x = returner(foo{}).get();
}

live example on wandbox.org


  • Is it guaranteed to foo{}be alive throughout the expression returner(foo{}).get()?

  • Or foo{}will it be alive only for returner(foo{}), while causing undefined behavior when called impl::get()?


The standard says in [class.temporary] :

Temporary objects are destroyed as the last step in evaluating a complete expression that (lexically) contains the point at which they were created.

In [intro.execution]

Full expression

  • unreasonable operand

  • constant expression

  • init-declarator or mem-initializer, including component initializer expressions,

  • , , ([class.temporary]),

  • , .

, , foo{} returner(foo{}) returner(foo{}).get().

+4
1

:

[...] , .

, returner(foo{}).get(), returner(foo{}) returner(foo{}).get(), . :

, foo{} returner(foo{}).get()?

.

+10

Source: https://habr.com/ru/post/1691592/


All Articles