什么时候堆内存优先于堆栈内存

When is heap memory prefered over stack memory

我知道本地数组是在堆栈上创建的,并且具有自动存储持续时间,因为它们在函数结束时被销毁。它们必须具有固定大小:

{
   int foo[16];
}

使用运算符new[]创建的数组具有动态存储持续时间并存储在堆上。它们可以有不同的尺寸。

{
    const int size = 16;
    int* foo = new int[size];
    // do something with foo
    delete[] foo;
}

每个进程的堆栈大小都是固定的和有限的。

我的问题是: 从栈内存切换到堆内存是否有经验法则,以减少栈内存消耗?

示例:

切换到动态分配的合理限制在哪里?

有关堆分配的讨论,请参阅

Where is a reasonable limit to switch to dynamic allocation?

在几种情况下,包括:

  • 太大 automatic variables. As a rule of thumb, I recommend avoiding call frames of more than a few kilobytes (and a call stack 超过一兆)。如果您确定您的函数不可递归使用,则该限制可能会增加。在许多小型嵌入式系统上,堆栈非常有限(例如几千字节),因此您需要对每个调用帧进行更多限制(例如只有一百字节)。顺便说一句,在某些系统上,您可以将调用堆栈限制增加更多(可能增加到几千兆字节),但这也是一个系统管理员问题。

  • 非后进先出分配原则,这种情况经常发生。

请注意大多数 C++ 标准 containers allocate their data in the heap, even if the container is on the stack. For example, an automatic variable of vector type, e.g. a local std::vector<double> autovec; has its data heap allocated (and released when the vector is destroyed). Read more about RAII