I am looking at the following piece of linked list code I found online:
void DeleteAfter(Node **head){
if(*head==NULL){
return;
}else{
Node *temp = NULL;
temp = (*head)->next;
(*head)->next = (*head)->next->next;
delete temp;
temp=NULL;
}
}
I am not that skilled with C++, so this could be a bad question, but why is temp being set to NULL after being deleted? Is this a necessary step?
Setting pointers to NULL following delete is not universal good practice in C++. There are times when it is a good thing to do, and times when it is pointless and can hide errors. There are plenty of circumstances where it wouldn't help. But in my experience, it can't hurt.
In this case delete operation on one pointer would make only that pointer NULL (if delete was making pointer NULL) and the other pointer would be non-NULL and pointing to memory location which is free. The solution for this should have been that user should delete all pointers pointing to same location.
In object-oriented computer programming, a null object is an object with no referenced value or with defined neutral (null) behavior.
Actually, Both acts same until and unless you assign some value to uninitialized pointer. For Ex: int *p; int *q=NULL; => both same. int *p; *p=3; int *q=NULL, *q=3; => In case of uninitialized pointer, 3 will be stored to some random/garbage location(uninitialized pointer), Hence you ll get value=3.
It's unnecessary. Some people make a habit of doing this even when it has no result. An aggressive compiler optimizer will eliminate this code, so it doesn't actually do any harm. But I would have written:
void DeleteAfter(Node *head) {
if (head) {
Node *next = head->next;
if (next) {
head->next = next->next;
delete next;
}
}
}
Note I eliminated a useless level of indirection and added a check to make sure there's a "node after" to delete.
The rationale for the habit is that if a pointer always refers to either a valid object or is null, you can rely on null checks as equivalent to validity checks.
For this reason, Ada, a language often used in safety critical systems, initializes pointers to null and defines its delete
equivalent operator to set its argument null automatically. Your C++ is simulating this behavior.
In practice, the value of this discipline is not what you'd hope. Once in a long while it prevents a silly error. One nice thing, however, is that debugger displays of pointer content make sense.
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