I've already seen similar question: Destructor vs member function race .. but didn't find the answer for the following. Suppose we have a class owning some worker thread. Destructor of the class can look like:
~OurClass
{
ask_the_thread_to_terminate;
wait_for_the_thread_to_terminate;
....
do_other_things;
}
The question is: may we call OurClass's member functions in the worker thread as we are sure all these calls will be done before do_other_things in the destructor?
Yes you can. Destruction of member variables willonly start after do_other_things
completes its execution. It is safe to call member functions before object gets destructed.
Well, you kinda can do that, but it's easy to make a mistake this way. For example, if you do something like:
~OurClass
{
delete *memberPointer_;
ask_the_thread_to_terminate; // the thread calls OurClass::foo();
wait_for_the_thread_to_terminate;
....
do_other_things
}
void OurClass::foo()
{
memberPointer->doSomething();
}
you will be in trouble. It also makes it harder to read through the code. So you will have to be careful with the order of operations and stuff like that. In general if it's possible to change the architecture to avoid such complicated constructions, I would suggest to do it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With