tags:

views:

85

answers:

3

Possible Duplicate:
Is it worth setting pointers to NULL in a destructor?

Do I have to do something like so:

~MyClass()
{
delete[] my_data_;
my_data_ = nullptr;//DO I HAVE TO WRITE THIS LINE?
}

Thank you.

+2  A: 

No. Once the destructor has completed, there's no way of legally accessing that pointer, so it doesn't matter what its final value is.

Joe Gauterin
+2  A: 
delete[] my_data_;

Should do all you need, after you use this then setting my_data_ to nullptr is not necessary.

shuttle87
+1  A: 

No, it only clutters code, has no real use and can be even optimized away by the compiler. Anyway once the destructor returns the object lifetime ends and there're no legal ways to access it - trying to would result in undefined behavior anyway.

sharptooth
no legal ways, but there are always illegal ones. In bigger projects having dangling pointers here and there is something you can expect to get from time to time.
jdehaan
@jdehaan: Since the object lifetime has ended there's no guarantee that the storage it previosly occupied is not reused for some tother unrelated object, so relying on the pointer being null doesn't guarantee anything.
sharptooth
In debug builds the pointer will usually get overwritten with a known debug value, and in release builds the null assignment will usually get optimized out. So unless you're using very old or esoteric compiler, it's a total and utter waste of time.
Joe Gauterin
@sharptooth, yes, I now agree, it only gives a false sense of security.
jdehaan
@sharptooth Relying on the pointer being null is better than trying to use it when its pointing to invalidated data. In C where we cannot implement RAII, I'd actually consider setting pointers to null after freeing memory to be a good habit.
@stinky472: This question is specifically about member variables and their treatment in class destructor, isn't it?
sharptooth