I have the following example:
#include <iostream>
#include <functional>
struct Tmr {
typedef std::function<void(void)> Callback;
Callback cb;
Tmr(Callback cb_) :
cb( cb_ )
{
}
void timeout()
{
cb();
}
};
struct Obj {
struct Tmr t;
Obj() :
t( std::ref( *this ) )
{
}
void operator () ()
{
std::cout << __func__ << '\n';
}
};
int main(int argc, char *argv[])
{
Obj o;
o.t.timeout();
return 0;
}
This runs fine, but initially I had the constructor of Obj
as:
Obj() :
t( *this )
Which results in a runtime error. I guess this is because only a reference to the member function is stored in my callback, and not the object to call the member on.
What I don't understand is what std::ref
does when I do Obj() : t(std::ref(*this))
and why this makes the program work. Can anyone shed some light on what's going on and how it works ?