2

I tried the next code:

class JustClass
{
public:
    void JustFunc()
    {
        std::thread t(this->JustThread);
        t.detach();
    }

    void JustThread()
    {

    }

private:

};

It should not do any problems. I just call a function of my object to act like a thread. But I get the next error fot this:

The Eroor I get on the codoe above

But if Im doing that:

class JustClass
{
public:
    void JustFunc()
    {
        std::thread t(this->JustThread, 5);
        t.detach();
    }

    void JustThread(int just_var)
    {

    }

private:

};

Then now I get this Eroor:

Error   2   error C3867: 'JustClass::JustThread': function call missing argument list; use '&JustClass::JustThread' to create a pointer to member   c:\users\micha\onedrive\מסמכים\visual studio 2013\projects\project2\project2\source.cpp 58  1   Project2

Why is that weird behavior?

wrg wfg
  • 77
  • 6

1 Answers1

2

You pass member function pointers like this:

class JustClass
{
public:
    void JustFunc()
    {
        std::thread t(&JustClass::JustThread, this);
        t.detach();
    }
    void JustThread() {}
private:
};

For your second variation:

class JustClass
{
public:
    void JustFunc()
    {
        std::thread t(&JustClass::JustThread, this, 5);
        t.detach();
}
void JustThread(int just_var){}

If the function is overloaded, you will need to select which overload. See Jonathan Wakely's Answer to a related question. Also read this FAQ about pointers to member functions.

Community
  • 1
  • 1
WhiZTiM
  • 21,207
  • 4
  • 43
  • 68
  • If you mean why you can just pass non-member functions to `std::thread`, [see](http://stackoverflow.com/questions/42150125/why-must-i-use-address-of-operator-to-get-a-pointer-to-a-member-function/42150232#42150232) this question. Also read [this FAQ](https://isocpp.org/wiki/faq/pointers-to-members) – WhiZTiM Feb 17 '17 at 12:01