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

前端 未结 5 1053
北荒
北荒 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 15:45

    Given a slight modification of your example:

    class Foo{
        private:
            int x[100];
            int *y;
        public:
            Foo()
            {
               y = new int[100];
            }
            ~Foo()
            { 
               delete[] y; 
            }
    
    }
    

    Example 1:

    Foo *bar = new Foo();
    
    • x and y are on the heap:
    • sizeof(Foo*) is created on the stack.
    • sizeof(int) * 100 * 2 + sizeof(int *) is on the heap

    Example 2:

    Foo bar;
    
    • x is on the stack, and y is on the heap
    • sizeof(int) * 100 is on the stack (x) + sizeof(int*)
    • sizeof(int) * 100 is on the heap (y)

    Actual sizes may differ slightly due to class/struct alignment depending on your compiler and platform.

提交回复
热议问题