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?
A destructor is a member function that is invoked automatically when the object goes out of scope or is explicitly destroyed by a call to delete . A destructor has the same name as the class, preceded by a tilde ( ~ ).
Meaning, a destructor is the last function that is going to be called before an object is destroyed. Destructor is also a special member function like constructor. Destructor destroys the class objects created by constructor. Destructor has the same name as their class name preceded by a tilde (~) symbol.
A destructor takes no arguments and has no return type. Its address cannot be taken. Destructors cannot be declared const , volatile , const volatile or static . A destructor can be declared virtual or pure virtual .
No, constructor does not return any value. While declaring a constructor you will not have anything like return type. In general, Constructor is implicitly called at the time of instantiation. And it is not a method, its sole purpose is to initialize the instance variables.
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With