我刚开始玩 C++(熟悉其他语言),我想知道一些事情。
例如,当使用 new 创建一个动态大小的数组时,为什么它在超出范围时不会被删除,但具有固定大小的数组会被删除?
例如使用以下代码:
int foo()
{
int baz[5]; // Gets removed out of scope
int *bar = new int[5]; // Does not get removed, becomes a leak
}
因为 baz 和 bar 都是指向数组开头的指针,“运行时环境”不能对具有固定大小作为动态大小?
它不能做这样的事情有什么区别。
最佳答案
Why does dynamic memory not get cleaned when it is out of scope
因为动态内存的目的是在作用域结束后分配。当您需要在一个范围内分配内存,然后在另一个范围内使用和取消分配它时,将使用动态内存。
关于c++ - 为什么动态内存在超出范围时不被清理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21408730/