c++ - 为什么 C++ 编译器不立即删除超出生命周期的变量?

标签 c++

来自 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/

相关文章:

c++ - 在 Visual Studio 项目目录中找不到头文件

c++ - Valgrind:无效读取大小 8 错误

c++ - 交换优先级队列时尝试引用已删除的函数错误

c++ - 我应该像这样使用 constexpr 吗?

c++ - 使用 curl 和 C++ 的 Django 身份验证

c++ - 为什么/何时自动刷新 cout 缓冲区?

c++ - 编写 Nim 游戏

c++ - 如何交叉引用现有的 doxygen 文档?

C++ 在数学方程式中使用 E

c++ - 使用数组实现堆栈