Is it safe to create threads in constructor.
All threads uses data of the object in which they are created.
I am creating threads after initializing all the member variables.
CreateThread( NULL, 0, myThreadProc, this,0,NULL );
Edited 16-Jun-11 22:39pm
It would be unsafe to use virtual functions in C++ constructor (never try it). If you don't do this big mistake, why not? I would only recommend to start the thread later, not in constructor. This is not the rule, just easier to design your code properly.—SA
You may do that if you can safely handle (in your object logic) possible
I would say its perfectly fine to do so... I've had to create manager classes that start multiple threads and the constructor is where it makes most sense to do so. In a lot of cases, if your thread fails to start, you're going to end the application anyway.
The problem with constructors is that - without a return value - you have no easy way to pass an error state, and you may not throw an exception. So, as C. Pallini already pointed out, you have to deal with all possible causes of failure right within the constructor code.
This may become even trickier when your class contains virtual methods! As SAKryokov pointed out, it is not safe to call virtual methods in a constructor.
To answer your question: No. In general it is not safe. As a rule of thumb, the less functions you call in a constructor, the better! You can do it if you know what you're doing and are capable to deal with all error cases, but it's much safer to do this in a separate function.
This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)