vendredi 1 mai 2020

returning lambda that captures reference [duplicate]

In Cpp primer 5th Ed. p 393

If the function returns a lambda, then - for the same reasons that a function must not return a reference to a local variable - that lambda must no contain reference captures.

#include <iostream>
using namespace std;

auto foo(ostream &os) {
    auto f = [&os]() -> std::ostream& { os << "Hello World !" << endl; return os;};
    f();
    return f;
}
void main() {
    foo(cout);
    auto f = foo(cout);
    system("pause");
    f();
}

This code compiles without warning in msvc 2019. It also appears to run fine. The captured os referes to std::cout which exists outside of foo's scope. Is f() Undefined behaviour ? If yes, is auto f = foo(cout); also undefined behaviour (that is, the returning and assigning of the lambda) ?

Aucun commentaire:

Enregistrer un commentaire