问题描述
我在网上找到下面的链接列表代码:
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;
}
}
我不是那么熟练的C ++,是一个坏问题,但为什么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?
推荐答案
这是不必要的。有些人养成这样做的习惯,即使没有结果。一个积极的编译器优化器将消除这个代码,所以它实际上没有任何危害。但我会写:
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.
习惯的基本原理是,如果指针总是指向一个有效对象或者是null,你可以依靠null检查相当于有效性检查。
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.
因为这个原因,Ada是一种常用于安全关键系统的语言,它初始化指向null的指针,并定义 delete
等效运算符自动设置其参数null。你的C ++正在模拟这种行为。
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.
这篇关于C ++ - 为什么删除后将对象设置为null?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!