tags:

views:

279

answers:

10

Imagine I have a class that allocates memory (forget about smart pointers for now):

class Foo
{
public:
  Foo() : bar(new Bar)
  {
  }

  ~Foo()
  {
    delete bar;
  }

  void doSomething()
  {
    bar->doSomething();
  }

private:
  Bar* bar;
};

As well as deleting the objects in the destructor is it also worth setting them to NULL?

I'm assuming that setting the pointer to NULL in the destructor of the example above is a waste of time.

+6  A: 

Yes, it's a waste of time.

Artelius
+8  A: 

Since the destructor is the last thing that is called on an object before it "dies," I would say there is no need to set it to NULL afterwards.

In any other case, I always set a pointer to NULL after calling delete on it.

In silico
A: 

No, it ain't worth it.

But if you want to be consistent then you should probably do it.

What I would usually do is to create a Free function that I can use each time I need to free the allocated data (event more Free functions if needed). In those functions you are advised to set the pointers to NULL (or identifier to an invalid value).

Iulian Şerbănoiu
+1  A: 

Might actually be worth it for debugging reasons.

Viktor Sehr
Doesn't your compiler pattern-fill objects on destruction in debug mode?
avakar
Still, you might suspect a double destruction, and wanna see if this specific destructor has executed etc.
Viktor Sehr
+3  A: 

Generally, no, there is no need to set pointers to NULL explicitly after deleting them in the destructor - though it can be a handy aid during debugging when inspecting to class to indicate whether a resource has been correctly freed or not.

A common idiom is to declare a SAFE_DELETE macro, which deletes the pointer and sets it NULL for you:

#define SAFE_DELETE(x) delete (x); x = NULL

SAFE_DELETE(bar)

This is especially useful in cases where the pointer may later get reused.

Blair Holloway
We already have that macro and it's used in destructors everywhere which I think is probably overkill.
Rob
Deleting then in the *destructor*, not the constructor :)
MadKeithV
Oops. I accidentally your object. Fixed.
Blair Holloway
-1 for an unsafe macro. try "if (x->refs == 0) SAFE_DELETE(x)".Rather use:template <typename T>void SafeDelete(T* p=0; }
peterchen
Wow, my first downvote!! You're correct in that use of templates technically guarantees type safety, however, and would give you better compilation errors. Though, checking x->refs == 0 explicitly is not good form; it is better to perform the check in a helper function.
Blair Holloway
Blair the issue is not in the x->refs, but the --> if (anyCondition) SAFE_DELETE(x) <-- - x = NULL will always execute. If you insist on the macro (or can't use templates on your platform), a common workaround is --> #define SAFE_DELETE do { delete x; x=NULL; } while (0) <--- which avoids this type of macro problems.
peterchen
P.S. the downvote is on the post, not on you personally ;)
peterchen
A: 

It's good practice to always set pointers to NULL after deleting them. Also some code checking tools enforce this.

humbagumba
It is a bad practice, it hides double delete bugs.
Hans Passant
There is a significant difference between *after deleting them* and *in the destructor*.
peterchen
A: 

I think it's always worth doing this (even though you don't technically need to). I set a pointer to NULL to indicate the memory it points to does not need to be deallocated.

Also if is useful for checking the pointer is valid before using it.

if (NULL == pSomething)
{
  // Safe to operate on pSomething
}
else
{
  // Not safe to operate on pSomething
}

Putting NULL first in the if condition guards against indavertently setting pSomething to NULL when you slip and miss out the second '='. You get a compile error rather than a bug that takes time to track down.

TortoiseTNT
Where are you going to check if that pointer is NULL? After the object was destroyed, its members no longer exist. You can't do anything with them anymore, not even check if they're NULL. You should only set a pointer to NULL when the pointer itself continues to exist, but not the pointed-to object.
MSalters
+1  A: 

First of all, this is a C practice, and a controversed one. Some argue (for C) that it hides bugs that would surface sooner if it was not used, and it's impossible to distinguish the use of a freed memory portion from the use of one that was never allocated...

Now in C++ ? It's useless, but not for the same reason than in C.

In C++ it's a bug to use delete. If you were to use smart pointers, you would not be worried about this, and you would not risk leaking (ie: are you sure your copy constructor and assignement operator are exception safe ? thread safe ?)

Finally, in a destructor it really is completely useless... accessing any field of an object once a destructor has run is undefined behavior. You've released the memory, so there could perfectly be something else written there, overwriting your carefully placed NULL. And in fact, the way memory allocators work is often to reallocate first the freshly deallocated zones: this enhance caching performances... and this is even truer (haha!) if we're talking about the stack, of course.

My opinion: SAFE_DELETE is a sign of impending doom.

Matthieu M.
+3  A: 

You shouldn't, for two reasons:

  • it aids debugging, but in modern environments, deleted objects are usually overwritten already with a recognizable bit pattern in debug builds.

  • In a large application, it may significantly degrade shutdown performance. In a worst-case scenario, closing your app means calling dozens of distinct destructors, and writing to hundreds of heap pages that are currently swapped to disk.

peterchen
+1  A: 

IMO its worth it in DEBUG mode. I do find it helpful frequently. In RELEASE mode it is usually skipped by the compiler due to code optimization, so you shouldn't really rely on this in your production code.

AOI Karasu