views:

288

answers:

3

When I'm inside a destructor is it possible that some other thread will start executing object's member function? How to deal with this situation?

+15  A: 

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.

DJClayworth
Perfect, simple answer. Taken further, not only can this happen inside the destructor, it can happen after you've left the destructor. The language can't fix bad design.
Shmoopty
Thank you. I should however suggest that Douglas Leeder's answer is more complete than mine.
DJClayworth
+13  A: 

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 the code owns the object, and it's responsible for deleting when no-one is using the object.
  2. Make the object reference counted - by added explicit reference counting code, or finding an appropriate base-class that implements reference counting
Douglas Leeder
A good hint would be using `boost::shared_ptr<>` for ref-counting. It also supports constructs like `weak_ptr<>` or `enable_shared_from_this`, which makes some good parts of lifetime-management quite easy.
gimpf
+1  A: 

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.

If your object is being shared by more than one thread, then an exception shouldn't be triggering its destruction.
Eclipse