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
, , foo{}
returner(foo{})
returner(foo{}).get()
.