Using boost thread and a non-static class function

The this keyword is used with boost::bind when the function object you’re creating is bound to a object member function. Member functions can’t exist apart from instances, so when creating a functor object out of a member function with boost::bind, you need a pointer to an instance. That’s exactly what the this keyword actually is. If you use the this keyword within a member function of a class, what you get is a pointer to the current instance of that class.

If you were to call bind from outside a class member function, you might say something like:

int main()
{
  Foo f;
  boost::thread* thr = new boost::thread(boost::bind(&Foo::some_function, &f));
}

Here, we’re using Foo::some_function as our thread function. But we can’t use this because we’re calling bind from main. But the same thing could be achieved using this if we called bind from within a member function of Foo, like so:

void Foo::func1()
{
  boost::thread* thr = new boost::thread(boost::bind(&Foo::some_function, this));
}

If a member function is static, or is simply a regular (non-member) function, then you don’t need an instance pointer at all. You would just do:

boost::thread* thr = new boost::thread(some_regular_function);

Leave a Comment