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

三世轮回 提交于 2019-12-04 04:46:26

问题


Let's say I have:

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

And I allocate an A instance like:

A *a = new A();

Does a.x and a.y are also allocated in the heap, since they are 'dependent' of a heap allocated object?

Thank you.


回答1:


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.




回答2:


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 ... |
        +-------+-----------------------+


来源:https://stackoverflow.com/questions/12826722/are-the-members-of-a-heap-allocated-class-automatically-allocated-in-the-heap

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!