Is the assignment and check for null explicitly required in the below snippet to achieve the same result. Also, is there anything wrong or can be improved here.
class Sample
{
private:
char *bits;
public:
Sample()
{
bits = NULL; //should this be explicit?
}
~Sample()
{
if (bits != NULL)
{
delete [] bits; //should this be explicit?
}
bits = NULL; //should this be explicit?
}
};
In the first case, where you do this in the constructor:
Whether or not you need this assignment depends on your code – if
bitsmay not have any memory allocated to it at all, then theNULLassignment should be there because of thedeletein the destructor. And really as a safety issue, you would probably want theNULLunless you document some contract the user has to obey, but here since you are initializing the pointer toNULL, I will assume that meansbitscould realistically beNULLor actually havenew-allocated memory at some point.If you did not initialize the pointer, and it is never subsequently made ‘valid’ by being assigned something, and the object is destroyed, then bad stuff happens.
Also, as a habit, prefer to use initialization lists when possible in constructors:
For the destructor, you do not need to check if a pointer is not
NULLbefore deleting it.deleteon aNULLpointer is completely safe. You also don’t need to reassign thebitspointer back toNULL, the object is going away.Of course, if you
deletean invalid pointer, then bad stuff will happen regardless.