gpt4 book ai didi

c++ - 当内存空间被删除时,指针的值保持不变还是被改变?对象内容是否会改变?

转载 作者:行者123 更新时间:2023-11-28 06:18:42 25 4
gpt4 key购买 nike

<分区>

class Node{
int a;
Node* next;
Node():a(20),next(NULL){};
};

int main()
{
Node* p = new Node;
p->next = new Node;
Node* q = p->next;

**delete q; (or delete p->next;)**

cout << q << endl; // always changed to "0000 8123"
cout << &q->a << endl; // 0000 8123
cout << &q->next << endl; // 0000 8127

cout << q->a << q->next << endl; // error! why it is ok to access their address and no to access their value?

cout << p->next << endl; // p->next no change , why ?
cout << p->next->a << endl; // changed to "DDDD DDDD"
cout << p->next->next << endl; // changed to "-5726 2307"

return 0;
}

我知道指针 p 和 q 在栈上,对象在堆上。

delete q; q 被更改为指向堆栈中的对象;
delete p->next; 为什么 p->next 的值没有改变?

删除的具体过程是什么?

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com