0

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.

1 Answers1

3

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.

Miles Budnek
  • 28,216
  • 2
  • 35
  • 52
  • Also note that a pointer to a member is not an actual "pointer" type. It does not match a `T*` type in template. – curiousguy Nov 28 '19 at 15:59