Destructor versus member function race

When I'm inside the destructor, is it possible that some other thread will start to perform a member function of the object? How to cope with this situation?

+7
c ++ multithreading destructor
source share
3 answers

C ++ has no internal protection from using an object after it is deleted - forget about the race state - another thread may use your object after it is completely deleted.

Or:

  • Make sure that only one place in the code belongs to the object, and that is responsible for deleting when no one uses the object.
  • Do the counting of objects - an explicit reference counting code is added or search for a suitable base class that implements reference counting
+17
source share

You should not destroy the object if you are not sure that you will not try to use it anymore - ideally, nothing else refers to it. When you call delete, you will need to take a closer look.

+15
source share

If you are in the destructor due to stack expansion in the exception handler, I suggest reordering your code so that you disable exceptions in the serialized block.

After the block, you check if the object is really valid, and call your method. Thus, an exception from one thread will allow other threads to correctly handle the call to the destructor.

+2
source share

All Articles