'How to pass member function of class to thread?

What is the correct way of passing a member function to thread

class foo{
public:
int sum(int a ,int b)
  {
    std::cout<<a+b;
  }
};

i need to pass this function to a thread in my main function.I have seen an example

#include <thread>
#include <iostream>

class SayHello
{
public:
    void greeting(std::string const& message) const
    {
        std::cout<<message<<std::endl;
    }
};

int main()
{
    SayHello x;
    std::thread t(&SayHello::greeting,&x,"goodbye");
    t.join();
}

why do we need to pass the reference to the object in this case?

c++


Solution 1:[1]

why do we need to pass the reference to the object in this case?

A member function, apart from the "normal" arguments, also takes a pointer to the object (this). This one is implicitly provided when you call with the normal syntax:

x.apply_greeting("goodbye"); //secretly calls apply_greeting(&x,"goodbye"). (not valid code!)

So when you have a pointer to a member function which you have when you write &SayHello::greeting, you need to provide the pointer to the object as well. Otherwise - how would it know about its member variables?

Pointer to member functions are messy, you can circumvent by using a lambda:

std::thread t([&x](){ x.greeting("goodbye!"); } );

Solution 2:[2]

I know it's not a perfect answer to the question. But in my experience of C++03, manage member functions is a hard work, especally when the code is shared with beginners in C++. My habit is the following:

class SayHello
{
  public:
    void greeting(std::string const& message) const
    {
      std::cout << message << std::endl;
    }
};

void apply_greeting(SayHello const* say_hello, std::string const* message)
{
  say_hello->greeting(*message);
}

int main()
{
  SayHello x;
  const std::string message = "goodbye";
  std::thread t(apply_greeting, &x, &message); // I'm not sure for this line, my habit is C++03 with boost::thread and boost::bind
  t.join();
  return 0;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2