Destructor vs member function race Destructor vs member function race multithreading multithreading

Destructor vs member function race


C++ has no intrinsic protection against using an object after it's been deleting - forget about race conditions - another thread could use your object after it's been completely deleted.

Either:

  1. Make sure only one place in thecode owns the object, and it'sresponsible for deleting when no-oneis using the object.
  2. Make theobject reference counted - by addedexplicit reference counting code, orfinding an appropriate base-classthat implements reference counting


You shouldn't be destroying an object unless you are sure that nothing else will be trying to use it - ideally nothing else has a reference to it. You will need to look more closely at when you call delete.


In case are you in a destructor because of stack unwinding in exception handler, I suggest rearranging your code in such a way that you trap exceptions within a serialized block.

After the block you check if the object is still valid and call your method. That way the exception in one thread, will allow other threads to handle call to destructor gracefully.