简体   繁体   中英

C++ Thread "Call to non-static member function without an object argument"

The scenario: I am trying to use three threads to execute a non static member function of objects contained within another object. The code does not compile, I get the error "Call to non-static member function without an object argument", even though I pass a pointer to each object. I also tried using std::ref().

#include <iostream>
#include <thread>
#include <vector>

class B {
public:
    int val;

    B(int i) : val(i) {};
    void show_val() {
        std::cout << val << std::endl;
    }
};

class A {
public:
    std::vector<B> bs;

    void add_b(int i) {
        bs.push_back(B(i));
    }
    void do_someting() {
        {
            thread t1(B::show_val(), &(a.bs[0]));
            thread t2(B::show_val(), &(a.bs[1]));
            thread t3(B::show_val(), &(a.bs[2]));
            t1.join();
            t2.join();
            t3.join();
        }
    }
};

int main() {
    A a;
    a.add_b(1);
    a.add_b(2);
    a.add_b(3);
    a.do_someting();
    return 0;
}

I can't find much on this specific problem. Usually this kind of code works for me when I call from within the class B itself and pass this pointer to the thread constructor.

B::show_val() is a function call . You don't want to call B::show_val , you want to take its address: &B::show_val .

Note that the & is required. Non-static member functions are not implicitly convertible to a pointer-to-member-function, unlike free functions and static member functions, which are implicitly convertible to function pointers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM