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

前端 未结 2 951
伪装坚强ぢ
伪装坚强ぢ 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条回答
  •  梦毁少年i
    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.

提交回复
热议问题