markzzz
markzzz

Reputation: 47995

Why "non-standard syntax; use '&' to create a pointer to member" using thread within a CTOR?

Here's the code:

#include <iostream>
#include <thread>

struct PickRandomFile {
    PickRandomFile() {
        std::thread t1(taskScanPaths);
    }

    inline void taskScanPaths() {
        // my task
    }
};

int main() {
    PickRandomFile pickRandomFile;

    return 0;
}

msvc says PickRandomFile::taskScanPaths': non-standard syntax; use '&' to create a pointer to member ThreadTrigger

What's wrong? I usually do it in gcc.

Upvotes: 0

Views: 132

Answers (1)

463035818_is_not_an_ai
463035818_is_not_an_ai

Reputation: 122830

Free functions "decay to pointers" (similar to arrays) so

std::thread t1(taskScanPaths);

would have been ok if taskScanPaths was a free function and it would have same effect as

std::thread t1(&taskScanPaths);

However, for class member function you need the address-of to get a pointer to the member function (and you need to specify the class), as in

std::thread t1(&PickRandomFile::taskScanPaths,this);

Also note that you need to pass a object/pointer to an instance so the thread can actually call the method.

Some relevant quotes from cppreference:

Pointer to member functions

A pointer to non-static member function f which is a member of class C can be initialized with the expression &C::f exactly. Expressions such as &(C::f) or &f inside C's member function do not form pointers to member functions.

It does not explicitly mention f, but as &f does not form a pointer to member function, it is kinda safe to assume f also does not form a pointer to member function.

On the other hand:

Pointers to functions

A pointer to function can be initialized with an address of a non-member function or a static member function. Because of the function-to-pointer implicit conversion, the address-of operator is optional:

Upvotes: 3

Related Questions