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

前端 未结 6 1087
野的像风
野的像风 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:34

    Each time you "instantiate" an object/symbol using a new (we are speaking C++ here), a new memory zone will be allocated for this object. If not, it will be put on the "local" memory zone.

    The problem is that I have no standard definition for "local" memory zone.

    An example

    This means that, for example:

    struct A
    {
       A()
       {
          c = new C() ;
       }
    
       B b ;
       C * c ;
    }
    
    void doSomething()
    {
       A aa00 ;
       A * aa01 = new A() ;
    }
    

    The object aa00 is allocated on the stack.

    As aa00::b is allocated on a "local" memory according to aa00, aa00::b is allocated inside the memory range allocated by the new aa01 instruction. Thus, aa00::b is also allocated on stack.

    But aa00::c is a pointer, allocated with new, so the object designed by aa00::c is on the heap.

    Now, the tricky example: aa01 is allocated via a new, and as such, on the heap.

    In that case, as aa01::b is allocated on a "local" memory according to aa01, aa00::b is allocated inside the memory range allocated by the new aa01 instruction. Thus, aa00::b is on the heap, "inside" the memory already allocated for aa01.

    As aa01::c is a pointer, allocated with new, the object designed by aa01::c is on the heap, in another memory range than the one allocated for aa01.

    Conclusion

    So, the point of the game is:
    1 - What's the "local" memory of the studied object: Stack of Heap?
    2 - if the object is allocated through new, then it is outside this local memory, i.e., it is elsewhere on the heap
    3 - if the object is allocated "without new", then it is inside the local memory.
    4 - If the "local" memory is on the stack, then the object allocated without new is on the stack, too.
    5 - If the "local" memory is on the heap, then the object allocated without new is on the heap, too, but still inside the local memory.

    Sorry, I have no better vocabulary to express those concepts.

提交回复
热议问题