號
讓我們一行一行:
x = new int(5); //allocate an integer, set it to 5 and return a pointer to it (x will not nullptr).
int* y; //allocate local storage to another pointer.
y = x; //copy the (not nullptr) value of x into y.
delete x; //de-allocate the space previously allocated.
//At this point the value of x is unchanged and y is equal to it.
//De-referencing x (*x) however is undefined because it was deallocated.
x = nullptr; //Set x to nullptr. Has no effect on y.
cout <<(y==nullptr)<< endl; //y still equals the (now invalid) value allocated above.
分配給另一個變量的變量是一次性的事情。之後,更改爲一個不會反映在另一個(雖然更改'通過'可能會影響另一個)。
你有兩個不同的變量,每個包含*副本*對方(最初)的。這就像有例如'int x = 5; int y = x; x = 0;'然後想知道爲什麼'y'不等於'0'? –
我不明白downvoting。這是一個可編輯的例子,寫得很好。請不要以顯而易見的理由倒下。 – Bathsheba
如何在刪除之前檢查y是否指向損壞的內存? – JukesOnYou