Reputation: 689
Is it a good technique to perform important/critical tasks of an object in the destructor? Such as:
class MyObject{
~MyObject() {
Execute();
}
void Execute() {...}
};
Upvotes: 0
Views: 238
Reputation: 11
Generally the answer is NO. E.g. if the program crashes, destructor won't be called. There're other circumstances when dtor isn't called. Destructor is dedicated method for clean up. Class users expect such behavior.
Upvotes: 0
Reputation: 7625
Destructors are meant to be a way to automatically clean up resources held by an object when it goes out-of- scope. Nothing else should be done in destructor. But the clean up may involve critical or complex processing. Also make sure exception does not leave your destructor. That will lead to terminate your program unexpectedly if the destrcutor was originally called because of stack unwinding due to another exception.
It is good practice to provide public interface for critical clean-up/resource management, so that client code can call it and handle if any exception arises. You can check if the clean up process is done in the destructor, if not perform it, but swallow any exception thrown.
To summarize, it is NOT a good practice to perform anything at all (whether critical or not) other than resource clean up in destructor.
Upvotes: 4