NULL In a Class Destructor [duplicate]
Possible Duplicate:
Is it worth setting pointers to NULL in a destructor?
Is it pointless to set a pointer (which allocates heap memory) to NULL
in the destructor?
class SampleClass
{
public:
SampleClass( int Init = 0 )
{
Value = new int( Init );
}
~SampleClass( void )
{
delete Valu开发者_如何学Ce;
Value = NULL; // Is this pointless?
}
int *Value;
};
While on the subject of classes, when should I use the explicit
keyword?
Yes. It is pointless, as the object is in the processing of being destroyed. Once it is destroyed, there will be no way to reach the pointer.
Yes, it is meaningless to set the pointer to NULL
at the very end of the destructor, as it will not exist anymore as soon as you leave the destructor.
You use the explicit keyword when you want to avoid implicit conversions to your class type. :-)
For example, if MyClass
has a constructor taking an int
, and a function f(const MyClass&)
, you can call f
either as
f(42)
or
f(MyClass(42))
If you make the constructor explicit, only the latter will work. It can save you from some unwanted implicit conversions.
It's not really pointless. While it's true that theoretically, the value can never be accessed again, setting it to NULL may well help you in the future if any other shenanigans start going on.
It is better to set the pointer to NULL.
If somewhere else in the code you delete the SampleClass instance and then access the Value (using another pointer to the same instance), you will know something went wrong because the program will crash on NULL dereference (so you will know you are accessing deleted object).
Otherwise you could keep using the deleted object and notice the bug only much later (when the memory is overwritten by another object). Such issues are often extremely difficult to debug.
精彩评论