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:
Sample()
{
bits = NULL;
}
Whether or not you need this assignment depends on your code - if bits
may not have any memory allocated to it at all, then the NULL
assignment should be there because of the delete
in the destructor. And really as a safety issue, you would probably want the NULL
unless you document some contract the user has to obey, but here since you are initializing the pointer to NULL
, I will assume that means bits
could realistically be NULL
or actually have new
-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:
Sample()
: bits(NULL)
{
}
For the destructor, you do not need to check if a pointer is not NULL
before deleting it. delete
on a NULL
pointer is completely safe. You also don't need to reassign the bits
pointer back to NULL
, the object is going away.
~Sample()
{
delete [] bits;
}
Of course, if you delete
an invalid pointer, then bad stuff will happen regardless.
class Sample
{
private:
char *bits;
public:
Sample() : bits(NULL) //always use member initialization list to init members
{
}
~Sample()
{
delete [] bits;
}
};
精彩评论