为什么我们需要在堆中创建一个对象

为什么我们需要在堆中创建一个对象

本文介绍了为什么我们需要在堆中创建一个对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我们可以使用堆栈满足所有需求?

why can we use the stack for all our needs?

注意:如果您在解释时举一个例子,那会非常好,因为通过例子更容易理解.

NOTE: it will be very good if you give an example while explaining because it is easier to understand with examples.

对不起,英语不好.

推荐答案

在实践中,调用堆栈有限且很小.典型的限制是几兆字节.相比之下,您通常可以在堆内存中分配千兆字节.

In practice the call stack is limited and small. The typical limit is a few megabytes. In contrast, you could often allocate gigabytes in heap memory.

而且,最重要的是,调用堆栈是一个堆栈,因此 LIFO (后进先出)纪律.在许多情况下,您想以与对象分配无关的顺序释放对象,或者只是按照先分配,先销毁"的顺序释放对象(这在堆栈中是不可能的).

Also, and most importantly, the call stack is a stack, so has a LIFO (last in first out) discipline. In many cases, you want to release objects in an order unrelated to their allocation or just in a "first allocated, first destroyed" order (and that is impossible on a stack).

考虑阅读一些有关垃圾回收的知识,例如 GC手​​册.它教您有关动态内存分配的有用概念和术语(即使对于使用手册的C程序也是如此)内存管理).另请参阅有关您的流程的虚拟地址空间(也请答案,至少在Linux中如此.

Consider reading something about garbage collection, e.g. the GC handbook. It teaches you useful concepts and terminology about dynamic memory allocation (even for C programs with manual memory management). Read also about the virtual address space of your process (se also this answer, at least for Linux).

动态内存分配的另一个优点是,同一可执行文件可以在各种计算机上运行(具有各种资源,尤其是不同数量的RAM),但无法处理相同数量的数据.如果您必须静态分配所有内存,则情况并非如此(例如,具有50 GB静态数据的C程序甚至无法在我的笔记本电脑上启动).

Another advantage of dynamic memory allocation is that the same executable can run on various computers (with various resources, in particular different amount of RAM), but won't be able to process the same amount of data. If you had to allocate all the memory statically, this would not be the case (e.g. a C program with 50 gigabytes of static data could not even start on my laptop).

这篇关于为什么我们需要在堆中创建一个对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 19:11