Are the members of a heap allocated class automatically allocated in the heap?

前端 未结 2 946
伪装坚强ぢ
伪装坚强ぢ 2021-01-20 04:25

Let\'s say I have:

class A{
    public:
    int x;
    int y;
};

And I allocate an A instance like:

A *a = new A();
         


        
相关标签:
2条回答
  • 2021-01-20 04:42

    It is important to understand that C++ uses "copy semantic". This means that variables and structure fields do not contain references to values, but the values themselves.

    When you declare

    struct A
    {
        int x;
        double yarr[20];
    };
    

    each A you will create will contain an integer and an array of 20 doubles... for example its size in bytes will be sizeof(int)+20*sizeof(double) and possibly more for alignment reasons.

    When you allocate an object A on the heap all those bytes will be in the heap, when you create an instace of A on the stack then all of those bytes will be on the stack.

    Of course a structure can contain also a pointer to something else, and in this case the pointed memory may be somewhere else... for example:

    struct B
    {
       int x;
       double *yarr;
    };
    

    In this case the structure B contains an integer and a pointer to an array of doubles and the size in memory for B is sizeof(int)+sizeof(double *) and possibly a little more. When you allocate an instance of B the constructor will decide where the memory pointed by yarr is going to be allocated from.

    The standard class std::vector for example is quite small (normally just three pointers), and keeps all the elements on the heap.

    0 讨论(0)
  • 2021-01-20 04:52

    You will get one allocation on the heap that contains x and y. A is just a nice way to refer to that object.

    I wish I could easily draw on Stack Overflow, but you can think of it something like this (very small) heap example:

            +-------------------------------+
            |            Heap               | 
            +-------------------------------+
            | Other memory here ...         | 
            +-------+-----------------------+
    A *a -> | x | y | Other memory here ... |
            +-------+-----------------------+
    
    0 讨论(0)
提交回复
热议问题