Inspired by this question.
Suppose in C++ code I have a valid pointer and properly delete
it. According to C++ standard, the pointer will become invalid (3.7.3.2/4 - the deallocation function will render invalid all pointers referring to all parts of deallocated storage).
At least in most implementations it preserves the value and will store exactly the same address as before delete
, however using the value is undefined behavior.
Does the standard guarantee that the pointer will preserve its value or is the value allowed to change?
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).
Yes, it's totally fine to reuse a pointer to store a new memory address after deleting the previous memory it pointed to.
delete keyword in C++Pointer to object is not destroyed, value or memory block pointed by pointer is destroyed. The delete operator has void return type does not return a value.
Deleting a pointer will do nothing if the pointer set to NULL. It might be the reason to check for the NULL pointer that deleting a pointer which is already set to NULL may indicate bugs in the program.
No, it's not guaranteed and an implementation may legitimately assign zero to an lvalue operand to delete
.
Bjarne Stroustrup had hoped that implementations would choose to do this, but not many do.
http://www.stroustrup.com/bs_faq2.html#delete-zero
If, for whatever reason, you want to be sure the pointer variable is not changed by delete
, write:
delete p + 0;
I believe that most implementations will keep the value, only for the sake of having no reason to change it. But regardless of whether the value is kept, it's still a useless pointer, is it not?
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