如果 class 的成员,C++ 数组会导致崩溃

C++ array causes crash if member of class

我目前正在使用一个不是使用 STL 容器构建的特定库。在将某些函数重构为 类 时,我遇到了基于以下模式的堆栈溢出。

class Base
{
    float values[1920 * 1080]; // causes overflow
public:
    Base() {}
};

int main()
{
    float values[1920 * 1080]; // does not
    Base t;
}

我知道你可以为Base::values分配动态内存,但为什么在main中不会导致堆栈溢出,但在Base中,为什么堆栈[=23] =] Base 似乎小了很多?也许这很明显我只是想念。

(以上示例使用 Visual Studio 2017 编译,默认标志)

1920 * 1080 * sizeof(float) 足以炸毁堆栈。 (8 MB)

确保编译器不会通过设置元素删除值数组。

改变基数如下。

class Base {
    float * values;
    Base() {
         values = new float[1920*1080];
    }
    ~Base(){
         delete [] values;
    }
 }

同时修复复制和赋值运算符。