另一个 C++ 指针删除问题在以下示例中:
class Foo {
public:
int *p;
~Foo() {
delete p; p = NULL;
}
};
Foo *f1 = new Foo();
Foo *f2 = new Foo();
f1->p = new int(1);
f2->p = f1->p;
delete f2; // ok
delete f1; // no error?
为什么调用“delete f1”时没有出错?我不是两次删除了同一个地址(*p)吗?
如果我直接删除最后两行代码中的指针,我会得到错误。
delete f2->p; // ok
delete f1->p; // error!! *** glibc detected *** double free or corruption (fasttop) ***