Search code examples
c++multithreadingforward-declaration

forward declaration for thread function argument is not working


i am trying to write a sample program for a class which will perform RAII and will call the thread with self this pointer. but data type for thread function argument is declared as forward declaration ahead. Please have a look of the sample program -

#include <iostream>
#include <thread>

using namespace std;

class test; // **forward declaration**

void thfunc (test *p) {
    cout << p->value << endl;
    return;
}

class test {
    public:
        int value;
        thread t1;
        test () {
            value = 100;
            t1 = thread(thfunc, this);
        }
        ~test() {
            t1.join();
        }
};

int main () {
    test * p = new test;
    delete p;
    return 0;
}

This is giving an compilation error -

fwd.cpp: In function 'void thfunc(test*)':
fwd.cpp:9:11: error: invalid use of incomplete type 'class test'
fwd.cpp:6:7: error: forward declaration of 'class test'

To Fix this, i made the thread function as static member function of the class -

class test {
    public:
        int value;
        thread t1;
        test () {
            value = 100;
            t1 = thread(thfunc, this);
        }
        ~test() {
            t1.join();
            cout << "Dtor" << endl;
        }
        **static** void thfunc (test *p) {
            cout << p->value << endl;
            return;
        }

};

Is this a correct fix? I want to make thread functions as separate library, but now i have to make them as a part of class. Please suggest. Any kind of help/pointer/suggestions will be appreciated.


Solution

  • Making thfunc a static member is correct in the sense it will work. If you wanted to keep them separate for a reason (and sometimes there are very good reasons), then you can still do that.

    It's the function that can only declared before being passed as an argument to std::thread:

    #include <iostream>
    #include <thread>
    
    using namespace std;
    
    void thfunc (class test *p);
    
    class test {
        public:
            int value;
            thread t1;
            test () {
                value = 100;
                t1 = thread(thfunc, this);
            }
            ~test() {
                t1.join();
            }
    };
    
    void thfunc (test *p) {
        cout << p->value << endl;
        return;
    }
    
    int main () {
        test * p = new test;
        delete p;
        return 0;
    }