另一个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)两次吗?
如果我直接删除最后2行代码中的指针,我会得到错误。
delete f2->p; // ok delete f1->p; // error!! *** glibc detected *** double free or corruption (fasttop) ***Another C++ pointer deletion question is in the following example:
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?Why I did not get error when calling "delete f1"? didn't I delete the same address (*p) twice?
If I directly delete the pointers in the last 2 lines of code, I will get error.
delete f2->p; // ok delete f1->p; // error!! *** glibc detected *** double free or corruption (fasttop) ***最满意答案
这是一件非常糟糕的事情。 但是C ++不一定会在这里做任何事情。 这是“未定义”的行为。 这并不意味着它会崩溃,但它很可能会导致糟糕的事情发生。
编辑:此外,在你的第二个例子中,它崩溃的事实只是“未定义”行为的一部分。 关于反应将会是什么不确定。
It is a VERY bad thing to do. However C++ won't necessarily do anything here. It is "un-defined" behaviour. That doesn't mean it will crash but it will, most probably, cause bad shit (tm) to happen.
Edit: Furthermore in your 2nd example the fact it crashes is just a part of "undefined" behaviour. It is undefined as to what the reaction will be.
更多推荐
发布评论