由多个对象指向的内存的多个C ++删除(Multiple C++ deletion of a memory pointed by multiple objects)

系统教程 行业动态 更新时间:2024-06-14 17:02:18
由多个对象指向的内存的多个C ++删除(Multiple C++ deletion of a memory pointed by multiple objects)

另一个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.

更多推荐

本文发布于:2023-04-21 18:53:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/dzcp/e944593899593dab79ac90b7d45a5660.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多个   对象   内存   Multiple   deletion

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!