这是如何运作的?指向指针赋值的指针

How does this work? Pointer to pointer assignment

#include <iostream>
using namespace std;
int main() {
    int *p1;
    p1 = new int;
    int *p2;
    p2 = new int;
    p2 = p1;    // what happens here?
    *p1=5;
    cout << "pointer 2 is " << *p2 << endl << *p1 << endl;  // both give out 5
    delete p1;  // what happens to p2 ?
    cout << "pointer 2 is " << *p2 << endl;
    delete p2;
    return 0;
}

删除指针对象p1会发生什么?指针 p2 现在引用什么?有人可以解释一下吗?感谢帮助

What is pointer p2 referencing now ?

没有。它是悬空的。它 指向相同的东西 p1 指向,但你已经删除了它。

因此,你的 *p2 和你的 delete p2 都坏了;这些都有未定义的行为。

您还泄露了第二个 new int,因为 p2 曾经指向它但在您写 p2 = p1 时停止这样做(您将其更改为指向 first new int 而不是,就像 p1 那样),并且没有其他方式可以引用它。

p2 = p1;    // what happens here?

您只是将p1(指向的内存地址)复制到p2。这与这样做没有什么不同:

int i1, i2;
i1 = 12345;
i2 = i1;

但是,因为 value 在分配给 new 的内存地址中有问题,您现在有内存泄漏,因为您丢失了指向第二个分配 intp2 之前指向。现在 p1p2 都指向内存中的第一个 int

cout << "pointer 2 is " << *p2 << endl << *p1 << endl;  // both give out 5

是的,因为 p1p2 指向相同的内存地址。

delete p1;  // what happens to p2 ?

这里 p2 没有任何变化,它仍然指向与之前相同的内存地址。 p1p2 是自变量,因此对其中一个的更改不会影响另一个。但是,delete 已经释放存储在 p1p2 指向的内存地址的第一个 int,所以现在它们都是 指向无效内存的悬空指针。由于您在此之后不使用 p1,因此 p1 没问题,但对于 p2 接下来的语句:

cout << "pointer 2 is " << *p2 << endl;
delete p2;

将导致未定义的行为,因为您正在通过悬空 p2 访问无效内存。读取 可能 成功 returning 仍然存在于内存地址的陈旧数据,或者它 可能 return垃圾,否则它 可能 崩溃。 delete 几乎肯定会崩溃,因为内存早先已经被释放了,但这也不能保证。 Undefined Behaivor 就是 - undefined - 所以几乎任何事情都可能发生。