{
int a = 10;
int *p = new int;
{
int *o = new int;
int *q = new int;
*o = 8;
*q = 4;
*p = 5;
p = q; // 'p' and 'q' now point at the same memory address
delete o; // memory pointed at by 'o' is freed now
}
{
*p = 1; // the memory address of 'p' (and 'q') holds the value '1'
delete q; // now the part I don't understand, if I delete q, is p deleted automatically?
p = &a; // then how come i still can use it after 'delete q'?
}
*p = 2;
}
*p = 6;
delete p; // I need that line, right?
01. {
02. int a = 10;
03. int *p = new int;
04. {
05. int *o = new int;
06. int *q = new int;
07. *o = 8;
08. *q = 4;
09. *p = 5;
10. p = q;
11. }
12.
13. {
14. *p = 1;
15. p = &a;
16. }
17. *p = 2;
18. }
في 14/ذو الحجة/1432 09:29 م، قال عبد اللطيف حاجي علي بهدوء وتؤدة:
الآن عندما نخرج من آخر سطر 18 فإننا نفقد جميع المتغيرات بما فيها p. فهل هذا يعني أننا يجب أن ننادي delete? الجواب طبعاً لا ﻷن p الآن يؤشر إلى a الذي تم حجزه على الـ stack.int *p = new int;
*p = 5;
delete p;
*p = 2;