Is below code standard-correct? (godbolt)
I.e. by-ref capturing a forwarding reference that represents a temporary, and returning the resulting lambda by-value from the function, within the same expression.
Of course storing the lambda for later use would make it contain a dangling reference, but I'm referring to the exact usage inside main
.
The doubts I'm having relate to this SO answer and potentially this language defect. Specifically there is one daunting comment that says "the reference capture lifetime rule in the standard references captured variables, not data, and their scope" - this appears to say a captured reference to a temporary might be invalid in my code.
#include <stdlib.h>
#include <string.h>
#include <cassert>
template<typename F>
auto invoke(F&& f)
{
return f();
}
template<typename F>
auto wrap(F&& f)
{
return [&f]() {return f();}; // <- this by-ref capture here
}
int main()
{
int t = invoke(wrap(
[]() {return 17;}
));
assert(t == 17);
return t;
}