armundle
armundle

Reputation: 1179

Is having a function call within a destructor a good practice?

Suppose there is a destructor for an object as:

anObject::~anObject()
{
    _functionCalledfromDestructor=1; //this sets the flag = 1
    functionCall(); //this function does something different than usual
                    //on seeing the flag
}

My question:

Is this style/method of coding in the destructor a good practice?

Upvotes: 1

Views: 563

Answers (4)

Mare Infinitus
Mare Infinitus

Reputation: 8182

Calling functions inside a destructor is commonly not considered a good practise, as there is the possibility that an exception is thrown. This leads to not correctly cleaned up memory and the behaviour of exceptions in the destructor is undefined.

Here is more information about throwing exceptions in the destructor:

SP on throwing in the destructor

In your case, a well defined clean up via a public interface is a whole better way to go. You could for example provide a Dispose method that does the clean-up.

Consider something like the following (in pseudocode):

public:
    void Dispose()
    {
        bool isDestructing = true;
        functionCall(isDestructing);
    }

Upvotes: 0

Roddy
Roddy

Reputation: 68033

Generally, no. I think you're better off doing something like this:

class anObject 
{
private:
  void doSomethingInternal(bool fromDestructor) {...}
public:
  void doSomething() {doSomethingInternal(false);};
  virtual ~anObject() { doSomethingInternal(true); };
}

Upvotes: 4

Ernest Friedman-Hill
Ernest Friedman-Hill

Reputation: 81694

"Hidden channels" like this are always a bad idea. The behavior of a function shouldn't depend on invisible state. You could give the function an argument, and then pass one value in the destructor and another value everywhere else. You could use a default value for the more common case, if you wish.

Upvotes: 10

R. Martinho Fernandes
R. Martinho Fernandes

Reputation: 234484

Is this style/method of coding in the destructor a good practice?

If the function does two different things depending on where it's called from, then you have two functions, not one. Make the two functions actually be two functions and you don't need to ask this question.

Upvotes: 7

Related Questions