How do I pass an instance member function as callb

2020-07-11 09:17发布

问题:

This question already has answers here:
Closed 7 years ago.

Possible Duplicate:
Start thread with member function

I'm VERY new to C++. My experience has mostly been with javascript and java.

I'm using Xcode on Lion. The following code gives me a compilation error "Reference to non-static member function must be called; did you mean to call it with no arguments?"

class MyClass {
private:
    void handler() {
    }

public:
    void handleThings() {
        std::thread myThread(handler);
    }
};

I also tried this->handler, &handler, and other variations, but none of them worked. This code compiles though and accomplishes what I want it to:

class MyClass {
private:
    void handler() {
    }

public:
    void handleThings() {
        std::thread myThread([this]() {
            handler();
        });
    }
};

Why can't I pass a reference to a member function? Is my work-around the best solution?

回答1:

std::thread myThread(&MyClass::handler, this);
myThread.join();


回答2:

You can use std::mem_fun, if you dont want to use a lamda.

Are you able to do this?

std::thread myThread(std::mem_fun(&MyClass::handler),this);

std::thread accepts arguments to the function (which is the first argument) and this is passed as an argument to the mem_fun object, which then calls the handler function on this.

You could also quite simply do the below, courtesy - Start thread with member function

std::thread myThread(&MyClass::handler,this);


回答3:

Use lambda to access class members within a member function, you need to capture this. [this] is mandatory in below code:

void handleThings() 
{
    std::thread myThread([this]() {
        handler();
    });
}

You could capture this by reference but it's not as efficient as capturing it by value. because going through the reference requires double indirection (modulo compiler optimizations)

void handleThings() {
        std::thread myThread([&]() {
            handler();
        });
    }

Lambdas are usually a better choice than bind.

  • Easier for readers to understand.
  • More efficient.