成员函数的内存分配是堆栈还是堆? [英] Member function memory allocation stack or heap?

查看:66
本文介绍了成员函数的内存分配是堆栈还是堆?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试分配一个数组,如下所示:

I'm trying to allocate an array as follows:

class foo{
public:
    void func(){double arr[13][64][64][64];}
};

int main()
{
    foo* inst = new foo();
    inst->func();       
    return 0;
}

我对以下答案的印象很深刻:此类型的内存是否分配在堆还是堆栈上?将数组arr放置在堆上(因为类的实例在堆上).当我遇到细分错误时,情况似乎并非如此.如果我将a的声明更改为:double * arr =新的double [13 * 64 * 64 * 64];(并正确删除),然后一切正常.

I was under the impression from answer such as: Does this type of memory get allocated on the heap or the stack? that the array arr would be placed on the heap (as the instance of the class is on the heap). This doesn't seem to be the case as I get a segmentation fault. If I change a's declaration to: double* arr = new double[13*64*64*64]; (and delete it properly) then everything's fine.

这是怎么回事?

推荐答案

您正在将成员变量与在成员函数中声明的变量混淆.

You are confusing member variables with variables declared inside a member function.

class Foo {
  public:
    int arr[13][64][64][64]; //Will be allocated in the same memory as the instance

    void func() {
      int arr2[13][64][64][64]; //Will always be allocated on the stack
    };
};

因此,如果您有 Foo * foo = new Foo() arr 分配在堆上,因为整个 foo 对象都分配在堆上堆.另一方面, Foo bar(); 现在将 arr 分配在堆栈上,因为 bar 已分配在堆栈上.

So if you have Foo* foo = new Foo() arr is allocated on the heap because the whole foo object is allocated on the heap. On the other hand Foo bar(); now arr is allocated on the stack because bar is allocated on the stack.

调用 foo-> func() bar.func()将在堆栈中分配 arr1 数组.

Calling either foo->func() or bar.func() will allocated the arr1 array on the stack.

这篇关于成员函数的内存分配是堆栈还是堆?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆