I have a Thread class like bellow
class Thread {
public:
Thread();
~Thread();
void start();
void stop();
}
So i need to call destructor from stop() method, is it a good way to do that?
Use the obj. ~ClassName() Notation to Explicitly Call a Destructor Function. Destructors are special functions that get executed when an object goes out of scope automatically or is deleted by an explicit call by the user.
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 ( ~ ). For example, the destructor for class String is declared: ~String() .
Yes, the destructor is nothing more than a function. You can call it at any time. However, calling it without a matching constructor is a bad idea.
An explicit call to destructor is only necessary when an object is placed at a particular location in memory by using placement new. Destructor should not be called explicitly when the object is dynamically allocated because the delete operator automatically calls destructor. Example: CPP.
Technically yes, but be careful, you should not use the deleted object, this
and non-static members anymore:
delete this;
You can also call the destructor:
~Thread();
However, in a well designed code, you can avoid these types of self destructions.
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