我直接从托管语言开始,几乎没有使用 C++ 的经验,因此这个问题可能太基本了。
在像 .net 这样的托管语言中,GC 会释放内存。从我读到的内容来看,在 C++ 中,这是通过调用 delete 来完成的。但是释放内存有什么作用呢?它是否将内存位置的所有位都设置为零?或者它是否以其他方式告诉操作系统该内存可用于重用?
更新:我以前经历过这个,我知道 GC 做什么。但这不是我的问题。我不是要问 GC 是如何工作的。我想理解的是,你如何判断一些内存是空闲的?
delete does three different things:
Runs the destructor of the object (or of all objects in the array in the case of delete[]).
Marks the chunk of memory previously used by the object as free.
If possible, informs the operating system that a chunk of memory is free for other programs to use.
Your question is about #2 and #3 together, but they are very different things. To understand how #2 works, remember that the (typically) single "heap" provided by the operating system is segmented into smaller chunks of different sizes. When you allocate a chunk of memory with new, you get a pointer to a previously free part of the heap, and the runtime performs the necessary bookkeeping that marks that region as unavailable for further allocations. delete does the reverse: it performs the bookkeeping that marks the region as available again, optionally coalescing it with adjacent free regions to reduce fragmentation. Subsequent calls to new will consider that region when looking for free memory to return.
换句话说,询问释放内存时会发生什么情况是错误的。真正的魔法发生在簿记区域!要了解通用分配器的实现,请谷歌了解 malloc 的实现。
至于#3,这是一个可选步骤,在许多情况下无法执行。只能“归还”恰好位于已分配堆末尾的已释放内存。位于大区域之后的单个分配将消除回馈的可能性。