来自 Scope vs. Lifetime of Variable我们看到了来自 Alok 的 anser 部分:
Note that technically x does not exist beyond its scope however it might happen that the compiler did not remove the contents of x and one might be able to access contents of x beyond its scope through a pointer(as you do).However, a code which does this is not a valid C++ code. It is a code which invokes Undefined Behaviour. Which means anything can happen(you might even see value of x being intact) and one should not expect observable behaviors from such a code.
这很有趣。为什么不在变量 x
到达 }
时将其删除?
最佳答案
同理删除硬盘上的文件,为什么只是删除索引项而不是格式化文件?
这需要时间。
如果没有必要,删除内存是没有意义的。稍后当您创建另一个局部变量时,编译器将再次使用该内存块,但在此之前它只会忽略内容。
关于c++ - 为什么 C++ 编译器不立即删除超出生命周期的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39788134/