4

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?

1
  • Thanks guys for your answers. I've just been confused by the following statement from C++ standard: "Once a destructor is invoked for an object, the object no longer exists;"
    – a-b
    Apr 23, 2014 at 10:31

3 Answers 3

4

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.

2

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.

1
  • 2
    That’s why proper resource handing is important. The delete statement in the destructor is a classic mistake. Use smart pointers instead, this ensures that such a mistake cannot occur. Apr 23, 2014 at 10:16
1

The implicit destruction of any data members occurs after execution of the last explicit line of your destructor, so all those data members are still fully functional whilst you wait for the thread. Hence, you must only avoid any premature explicit destruction of any data members (as exemplified in SingerOfTheFall's pathological code).

1
  • I should remember the "pathological code" expression, sounds fancy ;) Apr 23, 2014 at 10:22

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.