Does std::function keeps a reference to captured variables

121 views Asked by At

I'd like to understand why the following works:

class Foo {
public:
    using Callback = std::function<void(std::string& string)>;

    void setCallback(Callback&& callback) { windowInfo = callback; };
private:
    Callback windowInfo;
};

class Bar {
    Bar() { foo->setCallback([this](std::string& e) { sayHello(e); });}
    void sayHello(std::string& name) { //do something }

    Foo* foo;
};

Foo::setCallback asks for a function with no captures, however, I'm passing a lambda that captures Bar. I would expect the compiler to complain void(Bar, string) != void(string). Since I'm passing in a member function, it must implicitly pass the $this parameter as the first argument. Making the function signatures not equivalent.

EDIT

Why is that when I redefine using EventCallback as using EventCallback = void(Event& event); suddently this doesn't work anymore "no viable conversion from Application.cpp:10:34 to Foo::Callback aka (...)

Is std::function acting as the "glue" holding a reference to Bar but exposing the correct signature when requested?

0

There are 0 answers