Class members allocation on heap/stack?

后端 未结 3 1805
我寻月下人不归
我寻月下人不归 2020-12-16 01:45

If a class is declared as follows:

class MyClass
{
  char * MyMember;
  MyClass()
  {
    MyMember = new char[250];
  }
  ~MyClass()
  {
    delete[] MyMembe         


        
3条回答
  •  孤城傲影
    2020-12-16 02:20

    When you call new it allocates from the heap, otherwise it allocates from the stack (we'll ignore malloc and its ilk).

    In your first example, there will be space allocated in both: 4 bytes on the stack for the instance of MyClass (assuming 32-bit pointers), and 250 bytes on the heap for the buffer assigned to MyMember.

    In the second example, there will be 250 bytes allocated on the stack for the instance of MyClass. In this case, MyMember is treated as an offset into the instance.

提交回复
热议问题