Search code examples
c++multithreadingconstructorstdthread

No match for call while launching thread on constructor


I have a class Foo, that must launch a thread (which is a method loop() on my class) on the constructor.

My class is something like this on the header file:

class Foo
{
public:
  Foo();
  ~Foo();
private
  void loop();

  std::thread m_thread;

  //more stuff.
}

And the source file is:

Foo::Foo()
{
   m_thread(&Foo::loop, Foo()); // <---- No match for call '(std::thread) (void (Foo::*)(), Foo)'
   m_thread.join();
}

Foo::~Foo()
{
  m_thread.kill(); // <---- ??? how to do this?
}

void Foo::loop()
{
   while()
   {
       //do stuff.
   }
}

Question:

1 - How can I fix the error on the Foo constructor? I'm having the "no match for call" error when compiling.

Bonus question:

2 - How can I kill the thread on the destructor of the object?


Solution

  • 1) You're attempting to call a thread object, not initialize it here:

    m_thread(&Foo::loop, Foo());
    

    You should set assign it the appropriate value:

    m_thread = std::thread(&Foo::loop, Foo());
    

    But this will default-construct another Foo object, which will launch a thread, which will default-construct a Foo object, which will launch a thread, which will...

    So, maybe you mean to launch the thread on the instance itself, in which case you need

    m_thread = std::thread(&Foo::loop, this);
    

    Note that usually it is preferable to initialize data members in the constructor initialization list, but since the thread calls a member of Foo, it is best to launch it once the object has been constructed.

    2) You can join the thread in the destructor. Just make sure no exceptions propagate out of the destructor.