0

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.

hello
  • 1,168
  • 4
  • 24
  • 59
  • 5
    1) calling delete on a null pointer value results in a NOP (No-Operation) and is perfectly valid, acceptable, and generally preferred. 2) Use `std::vector` instead. No seriously, **use it**. – Captain Obvlious Jul 07 '15 at 00:14
  • Yes, I'm aware of `std::vector`, this is for learning purposes. – hello Jul 07 '15 at 00:16
  • 2
    possible duplicate of [Is there any reason to check for a NULL pointer before deleting?](http://stackoverflow.com/questions/615355/is-there-any-reason-to-check-for-a-null-pointer-before-deleting) – i_am_jorf Jul 07 '15 at 00:19

2 Answers2

6

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.

Captain Obvlious
  • 19,754
  • 5
  • 44
  • 74
0

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.

Nicholas Smith
  • 975
  • 7
  • 18
  • _"you should assign the pointer to NULL immediately afterwards"_ - Um yeah no. This is pretty pointless to do in a destructor since trying to delete an object twice is already undefined behavior. – Captain Obvlious Jul 07 '15 at 00:53