Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 Value;
            Value = NULL; // Is this pointless?
        }

        int *Value;
};

While on the subject of classes, when should I use the explicit keyword?

like image 277
DeadCapacitor Avatar asked May 03 '26 04:05

DeadCapacitor


2 Answers

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.

like image 156
EvilTeach Avatar answered May 05 '26 16:05

EvilTeach


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.

like image 35
Bo Persson Avatar answered May 05 '26 17:05

Bo Persson