Are data members allocated in the same memory space as their objects in C++?

前端 未结 6 1088
野的像风
野的像风 2020-12-03 09:09

Say I\'ve got a class like this:

class Test
{
  int x;
  SomeClass s;
}

And I instantiate it like this:

Test* t = new Test;         


        
6条回答
  •  孤城傲影
    2020-12-03 09:45

    class MyClass {
        int i;
        MyInnerClass m;
        MyInnerClass *p = new MyInnerClass();
    }
    
    MyClass a;
    MyClass *b = new MyClass();
    

    a is on the stack; its members a.i and a.m (including any members of a.m) and a.p (the pointer, not the object it points to) are part of it and so also on the stack.

    The object pointed to by a.p is on the heap.

    The object pointed to by b is on the heap, including all its members; and so is the object pointed to by b.p.

提交回复
热议问题