binary01
binary01

Reputation: 1898

Calling a member function pointer passed as template argument from lambda crashes

I have the following code:

#include <functional>

struct Foo {
    void Callback()
    {}
};

template <class T, class P>
std::function<void()> MemCB(T &t, P p) 
{
    //return [&]() {t.Callback();}; //no issues if done this way.
    return [&]() {(t.*p)();};
}


int main()
{
    Foo f;
    std::function<void()> func = MemCB(f, &Foo::Callback);
    func();
}

This crashes (at least with optimizations turned on), and the issue is the attempt to call the member function here:

 return [&]() {(t.*p)();};

What's happening that causes issues here ?

Is there any way I can pass in an object t and a pointer to a member function p like I tried here and call p on the t object ?

Upvotes: 0

Views: 32

Answers (1)

Jarod42
Jarod42

Reputation: 217663

You issue is that captured p become dangling "reference", change it to:

template <class T, class P>
std::function<void()> MemCB(T &t, P p) 
{
    return [&, p]() {(t.*p)();};
}

Upvotes: 1

Related Questions