Originally Posted by
Darryl
Yea, the if statements aren't needed as it is safe to delete a null pointer, however because the code provided doesn't set anything to null after deletion it does run the risk of calling delete a second time on a pointer that has already been deleted which is not so safe.
That only matters if there are additional references to the pointer.
If the pointers belong are members of a particular object the destructor need not set the pointers to NULL as it is guaranteed that the pointers will not be deleted twice.
For example;
Code:
class X
{
public:
X () : data(new int) {};
~X() {delete data;};
void Set(int a) {*data = a;};
void DoNothing() {};
private:
int *data;
};
int main()
{
X *x = new X;
delete x;
// it is impossible (without invoking undefined behaviour) to access the old x->data
x->Set(5); // one example of undefined behaviour
x->DoNothing(); // and another
}
Both of the calls x->Set(5) and x->DoNothing() invoke undefined behaviour because x is now a dangling reference. The technique of setting x to NULL after deleting it in main(), and then checking it before invoking member functions, will work. However setting data to NULL inside X's destructor does not change the fact that main() invokes undefined behaviour.
The only exception to the above is if the object x gives some other object the ability to hold a pointer to it's data member. But, even then, changing data to NULL in the destructor does not fix that unless the destructor somehow communicates with the object holding the dangling reference to data.
Incidentally, "destructor" is the more usual name for X~X(), not "deconstructor".