In what situations in the codes, should we delete
a given pointer
and where had we better assign zero
to it, instead of deleting
?
In what situations in the codes, should we delete a given pointer and where had we better assign zero to it, instead of deleting?
You delete a pointer if you created it using new
. And actually you are deleting an object to which the pointer points, not the pointer itself. Although syntax lets you write delete ptr
indeed. But what gets deleted is where ptr
points. Not ptr
.
Assigning nullptr
to the pointer, if you didn't do delete
before, doesn't help - you actually lose an address of object where that pointer was pointing and creating a memory leak (of course if there were no other pointers pointing to the original object). e.g. this is bad:
double* pvalue = new double;
..
pvalue = nullptr; // Bad - pointer to original memory is lost now
delete pvalue; // What should I delete?
So if you used new
for creating an object you need to delete
it before assigning a nullptr
to the pointer.
So after deleting
it is ok to assign nullptr
to the pointer.
All that said you need to consider if you really need dynamic memory allocation (e.g. new
) in your code.
I think that one should delete a pointer when the object it refers to is not needed anymore, after it has been created by using new
. And one can assign zero (preferably NULL
) to a pointer after it has been deleted to show it is not pointing to something anymore. One can then test afterwards whether or not a pointer equals NULL
.
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