Python代码:
class ListNode:
def __init__(self,x):
self.x = x
self.next = None
if __name__ == "__main__":
p = ListNode(1)
q = ListNode(2)
p.next = q
del q
print p.next.x //2
C++代码
#include <iostream>
using namespace std;
struct Node{
int x;
Node* next;
};
int main() {
Node* p = new Node();
p->x = 1;
Node* q = new Node();
q->x = 2;
p->next = q;
delete q;
cout<<p->next->x<<endl; //0
return 0;
}
由上面的代码可知,python中的del跟C++中的delete是不一样的,del不会无条件的清掉变量所指向对象的内存。
del 〈 object ,...〉
Each object is any kind of Python object. Usually these are variables, but they can be functions, modules, classes.
The del statement works by unbinding the name, removing it from the set of names known to the Python interpreter. If this variable was the last remaining reference to an object, the object will be removed from memory. If, on the other hand, other variables still refer to this object, the object won't be deleted.
The del statement is typically used only in rare, specialized cases. Ordinary namespace management and garbage collection are generally sufficient for most purposes.
参考: