当前位置: 动力学知识库 > 问答 > 编程问答 >

c++ - Destructor vs member function race again

问题描述:

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.

网友答案:

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).

分享给朋友:
您可能感兴趣的文章:
随机阅读: