mercredi 19 juin 2019

С++ wrapping lambda in another lambda inside a function

Basically, I'm having this code:

struct Receiver {
    void receive(std::function<void()> f) {
        func_ = f;
    }
    std::function<void()> func_;
};

void pusher(Receiver& r) {
    auto wrapper=[&](std::function<void()> w) {
        r.receive([&]() {
            cout << "Before" << endl;   
            w();
            cout << "After" << endl;    
        });
    };


    wrapper([&]() {
        cout << "Original" << endl; 
    });
}

int main() {
    Receiver r;
    pusher(r);
    r.func_();
    return 0;
}

There's a class which stores std::function and we store a function into that class. Function is created in a "wrapper" local lambda of another function.

The code prints "Before" and crashes. If I put the whole code inside "pusher" into main(), then everything works.

I suspect the problem us that when r.receive() is called, it contains reference to "w" which is invalid after returning from "pusher".

But I need to pass a lambda to a receiver which is created by "decoration" with another lambda.

How do I properly (in general) decorate a lambda with a reference to some local lambda and pass it somewhere else?

Aucun commentaire:

Enregistrer un commentaire