首页 > 解决方案 > 这是如何运作的?指向指针赋值的指针

问题描述

#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 引用的是什么?有人可以解释一下吗?谢谢您的帮助

标签: c++dynamic-memory-allocation

解决方案


现在指针 p2 引用的是什么?

没有什么。它悬空。它指向的是同一个东西p1但是你已经删除了它。

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

您还泄漏了 second new int,因为p2曾经指向它,但在您编写时停止这样做p2 = p1(您将其更改为指向第一个 new int,就像这样p1做一样),并且没有其他方法可以引用它。

关于指针的 OP 代码中发生的情况的粗略图


推荐阅读