因此,當我運行以下代碼時,我試圖了解記憶體的狀態。根據我的理解,一旦 if 塊結束,在 if 陳述句中初始化的左右兩個子樹應該被視為不存在。但是,當我運行此代碼時,if 塊內的輸出與 if 塊后的輸出相同。我認為這可能是由于系統實際上沒有洗掉分配的內容,而是簡單地更新了靜態記憶體指標。所以我分配了一個大陣列,希望能覆寫在 if 塊之后可能仍然存在的任何東西。但是,這似乎對輸出沒有任何影響。當我改為呼叫 test 函式時,在回傳 main 時,對子樹的 val 成員的訪問會輸出一些隨機值。這符合我的預期。
有人可以解釋發生了什么。為什么一個塊似乎沒有洗掉任何本地分配的記憶體,而一個函式似乎呢?
#include<iostream>
using namespace std;
class Tree {
public:
Tree(int init_val) : val{init_val} {};
Tree() = default;
Tree* left = nullptr;
Tree* right = nullptr;
int val;
};
void test(Tree* const tree) {
Tree left(10);
Tree right(20);
tree->left = &left;
tree->right = &right;
cout << "inside function:" << endl;
cout << "left = " << tree->left->val << endl;
cout << "left = " << tree->right->val << endl;
}
int main(int argc, char const *argv[]) {
Tree root;
int input;
cin >> input;
if(input > 10) {
Tree left(10);
Tree right(20);
root.left = &left;
root.right = &right;
cout << "inside if-statement:" << endl;
cout << "left = " << root.left->val << endl;
cout << "left = " << root.right->val << endl;
}
int arr[1000000];
//test(&root);
cout << "outside test and if-block:" << endl;
cout << "left = " << root.left->val << endl;
cout << "left = " << root.right->val << endl;
\
}
uj5u.com熱心網友回復:
假設您擁有一塊土地并在其中埋葬一具尸體。后來你把土地賣給別人。然后你想起尸體并嚇壞了,所以你晚上回去把它挖出來。幸運的是,它仍然存在。
是的,您擅自闖入,并不能保證您會找到它,但由于新主人尚未對他們的土地做任何事情,因此它仍然完好無損。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/390127.html
