[英]C++ access statically allocated objects' members
因此,当我运行以下代码时,我试图了解 memory 的 state。 据我了解,一旦 if 块结束,在 if 语句中初始化的左右两个子树应该被认为不存在。 但是,当我运行此代码时,if 块内的 output 与 if 块后的 output 相同。 我认为这可能是由于系统实际上并未删除分配的内容,而是简单地更新了 static memory 指针。 所以我分配了一个大数组,希望这会覆盖在 if 块之后可能仍然存在的任何内容。 但是,这似乎对 output 没有任何影响。 当我改为调用测试 function 时,返回 main 时,对子树的 val 成员的访问会输出一些随机值。 这符合我的预期。
有人可以解释发生了什么。 为什么一个块似乎没有删除任何本地分配的 memory,而 function 确实出现了?
#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;
\
}
假设您拥有一块 plot 的土地并在其中埋葬了一具尸体。 后来你把土地卖给别人。 然后你记得尸体并吓坏了,所以你 go 回来并在晚上把它挖出来。 幸运的是,它仍然存在。
是的,你侵入了,不能保证你会找到它,但由于新主人还没有对他们的土地做任何事情,所以它仍然完好无损。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.