Should destructors be threadsafe?

后端 未结 9 1325
误落风尘
误落风尘 2021-02-07 09:08

I was going through a legacy code and found the following snippet:

MyClass::~MyClass()
{
   EnterCriticalSection(&cs);

//Access Data Members, **NO Global**          


        
9条回答
  •  一个人的身影
    2021-02-07 09:45

    I think you have a more fundamental problem. It shouldn't be legal to destroy your object on one thread while another thread is still calling member functions. This in itself is wrong.

    Even if you successfully guard your destructor with critical sections, what happens when the other thread starts executing the remainder of the function? It will be doing so on a deleted object which (depending on it's allocation location) will be garbage memory or simple an invalid object.

    You need to alter your code to ensure the object is not destructed while still in use.

提交回复
热议问题