Is saying delete pointer
and pointer = nullptr
the same? Probably not, but does the latter free up memory? What about delete pointer; pointer = nullptr
/ pointer = nullptr; delete pointer
? Why not use that to make a safe way to delete pointers prematurely if required, where they would normally be deleted some other time and cause an error with a normal delete?
Delete operation performs a null pointer check anyway. So performing another null pointer check is an unnecessary operation and for me personally it makes the code ugly. But of course it is a good practice to set the pointer to NULL/nullptr after deleting as the pointer location is invalid after deletion.
The address of the pointer does not change after you perform delete on it. The space allocated to the pointer variable itself remains in place until your program releases it (which it might never do, e.g. when the pointer is in the static storage area).
What happens when delete is used for a NULL pointer? Explanation: Deleting a null pointer has no effect, so it is not necessary to check for a null pointer before calling delete.
We can use nullptr to explicitly initialize or assign a pointer a null value. In the above example, we use assignment to set the value of ptr2 to nullptr , making ptr2 a null pointer. Use nullptr when you need a null pointer literal for initialization, assignment, or passing a null pointer to a function.
pointer = nullptr;
is like removing the ink from a business card. You no longer know where the house is located, at least not from looking at that particular business card. But the house is still there.
delete pointer;
is like tearing down the house. The business card still tells you where that house used to be, but if you were to drive there (dereference the pointer), you would see the house was gone. Or worse, maybe they put up a nuclear waste storage facility at that address in the meantime.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With