Does this type of memory get allocated on the heap or the stack?

前端 未结 5 1051
北荒
北荒 2020-11-30 15:23

In the context of C++ (not that it matters):

class Foo{
    private:
        int x[100];
    public:
        Foo();
}

What I\'ve learnt tel

5条回答
  •  無奈伤痛
    2020-11-30 16:05

    Yes, the member array x will be created on the heap if you create the Foo object on the heap. When you allocate dynamic memory for Foo you are asking for memory of length sizeof(Foo) (plus possibly some memory overhead, but let's ignore that for the time being), which in your sample code implies the size of 100 ints. This has to be case for the lifespan of objects of type Foo (and their internal data) to cross scopes.

    If you don't create the Foo object on the heap, and the internal array of Foo isn't a pointer to which you allocate memory with new in Foo's constructor then that internal array will be created on the stack. Again, this has to be the case in order for the array to automatically be cleaned without any deletes when the scope ends. Specifically,

    struct Foo {
        int* y;
        Foo() : y(new int()) { }
        ~Foo() { delete y; }
    };
    

    will create y on the heap regardless of whether a Foo object was created on the stack or on the heap.

提交回复
热议问题