【发布时间】:2022-01-22 04:20:32
【问题描述】:
所以我在运行以下代码时试图了解内存的状态。据我了解,一旦 if 块结束,在 if 语句中初始化的左右两个子树应该被认为不存在。但是,当我运行此代码时,if 块内的输出与 if 块之后的输出相同。我认为这可能是由于系统实际上并未删除分配的内容,而是简单地更新了静态内存指针。所以我分配了一个大数组,希望这会覆盖在 if 块之后可能仍然存在的任何内容。但是,这似乎对输出没有任何影响。当我改为调用测试函数时,在返回 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;
\
}
【问题讨论】:
-
首先它是在栈上分配的,所以无论如何也不会被删除。至于它的值——仅仅声明数组
arr不会改变内存内容。它们只是指向同一个内存块(嗯,是重叠的内存块)。
标签: c++ object memory-management allocation