-1
#include <iostream>
#include <string>
using namespace std;
int main() {
string* pstr2 = new string;
cout << "pointer pstr2: " << pstr2 << endl;
delete pstr2;
cout << "pointer pstr2 after deletion: " << pstr2 << endl;
string* pstr = new string;
pstr->push_back('a');
cout << "pointer pstr: " << pstr << endl;
cout << "*pstr: " << *pstr << endl;
delete pstr;
cout << "pointer pstr after deletion: " << pstr << endl;
cout << "*pstr after deletion: " << *pstr << endl;
return 0;
}
輸出如下:c + +刪除指針
pointer pstr2: 0x7ffe00404d10
pointer pstr2 after deletion: 0x7ffe00404d10
pointer pstr: 0x7ffe00404d10
*pstr: a
pointer pstr after deletion: 0x7ffe00404d10
*pstr after deletion: a
問題:
我知道有一個慣例刪除指針後,設置動態指針爲NULL。但爲什麼pstr2仍然有有效的地址?
刪除指針pstr釋放內存,即「a」。但爲什麼* pstr仍然有效的內容爲「a」?
爲什麼pstr和pstr2具有相同的分配地址?我已經運行了幾次代碼。
可能重複的[爲什麼不刪除任何東西?](http://stackoverflow.com/questions/3280410/why-doesnt-delete-destroy-anything) – HazemGomaa
「刪除」取消分配在該位置的內存,這並不意味着刪除存儲在指針中的地址值。這就是爲什麼在刪除後將其設置爲NULL的原因。 – Mox
*但爲什麼pstr2仍然有有效的地址?* - 什麼是「無效地址」? – PaulMcKenzie