Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between delete-ing a pointer and setting it to nullptr? [duplicate]

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?

like image 917
Accumulator Avatar asked Jul 24 '15 20:07

Accumulator


People also ask

Should you set a pointer to nullptr after deleting it?

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.

What happens when you delete a pointer to a pointer?

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 if you delete nullptr?

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.

What does setting to nullptr do?

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.


1 Answers

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.

like image 108
fredoverflow Avatar answered Sep 30 '22 22:09

fredoverflow