SørenHN
SørenHN

Reputation: 696

Create thread via class constructor

Is it possible to create a thread with a function pointer to a class constructor?

If this is possible, when how would the class destructor get called?

I have made this example of what i am looking for:

class ClassA
{
public:
    ClassA(void* argPtr)
    { ... }
};

int main(void)
{
    pthread_t thread;
    pthread_create(&thread, NULL, &ClassA(), NULL);
    return 0;
}

Upvotes: 0

Views: 474

Answers (1)

user7860670
user7860670

Reputation: 37468

Constructors are classified as "special member functions", and it is not possible to get a pointer to constructor function because it does not have a name (note that you are using class name, not a constructor function name, to invoke it):

12.1 Constructors [class.ctor]

1 Constructors do not have names.

...

2 A constructor is used to initialize objects of its class type. Because constructors do not have names, they are never found during name lookup;

Also pthread_create takes a pointer to a regular function, not to a member function.

Upvotes: 3

Related Questions