Reputation: 4373
I'm studying about new
and new[]
from learncpp and there is one small detail in the site, which isn't clear enough for me. The following picture will explain my question:
So do we have to set the array-pointer also to 0 after we have deallocated it like in the single variable case? Is this a requirement or is the procedure different with delete
and delete[]
?
Thnx for any help! =)
Upvotes: 1
Views: 340
Reputation: 115
It very depends what you are planning to do further in the code. Setting a pointer to to NULL/nullptr after deleting the object it used to point to (regardless whether it is a pointer pointing to the array or to the singular variable), is done purely to mark a pointer as deallocated ,so you can easily check if that pointer is still 'active' or not by :
if (pnArray != nullptr)
{
// now it is safe to dereference the pointer
}
If the double deletion occurs in the code (shouldn't be the case), calling a delete operator on nullptr will not crash the program (double deletion may bring significant amount of pain: it may crash the application, corrupt the heap, make some changes to the objects already allocated on the heap..) :
delete pnValue;
pnValue = nullptr;
....
delete pnValue; // safe to delete ( still it's not no-op )
You don't need to set the pointers to nullptr-s if you delete the class members in it's destructor for instance (as that pointers will not be used anymore).
These are the raw pointers, maybe have a look also at the smart pointers, which are in general much safer option
Upvotes: 1
Reputation: 119174
You don't have to set a pointer to zero after any deallocation. This is simply done to make it easy to tell that the pointer no longer points to anything.
Upvotes: 4