0

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;
}
4
  • 3
    No, a constructor is not a function; its address cannot be taken. &ClassA() (if it even compiles) creates a temporary object and takes an address of that. Commented May 2, 2017 at 14:32
  • You can create a thread that calls a function that creates an instance of ClassA and will call its constructor. Commented May 2, 2017 at 14:36
  • What you can do so have a thread created in your constructor which then runs on your object - not quite the same; and can end up with other cans of worms being opened (the object isn't yet constructed!) Commented May 2, 2017 at 14:51
  • 1
    You may want to look up <thread>. Pthreads are for C, and don't understand C++. And in modern C++, you can call std::thread(&std::make_unique<ClassA>).detach(). Then the destructor will be called when the unique_ptr goes out of scope. Commented May 2, 2017 at 15:39

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.