Reputation: 1228
If I have two dynamic arrays as private data members:
std::string* first_array;
std::string* second_array;
I know I can simply delete like this in the destructor
myClass::~myClass()
{
delete[] first_array;
delete[] second_array;
}
The concern I have is this, not all the time do I have data inside both array, so is something like this considered best practice ?
myClass::~myClass()
{
if(first_array)
delete[] first_array;
if(second_array)
delete[] second_array;
}
I tried both and it both worked, not sure which one is better in terms of performance.
Upvotes: 0
Views: 294
Reputation: 1005
Deleting a pointer that may be NULL is perfectly ok. As already stated by others, calling delete on a NULL pointer results in a NOP.
However, after deleting any pointer, no matter where, why, how, or when, you should assign the pointer to NULL immediately afterwards. Failing to do this can lead to accidental double-deletion of the pointer, which is catastrophically bad for your program (https://isocpp.org/wiki/faq/freestore-mgmt#double-delete-disaster).
For the same reason that you would not initialize a pointer to some random address, you do not want to leave your pointer dangling in the wind after deleting it, just waiting to be the bullet in your foot.
Upvotes: 0
Reputation: 20063
The C++ Standard specifies calling delete
on a null pointer value will result in a NOP (No-Operation). It is perfectly valid, acceptable, and generally preferred.
Upvotes: 6