Local class variable location

2019-03-05 06:22发布

What happens if a class instantiates all it's local variables on the stack (ie: int i; //An integer on stack versus int *p; //Pointer to an int) while the class itself is instantiated on the heap? Where are the class members? Here's an example:

class A  {
  public:
  int a, b; //These are instantiated on the stack, if the line were written outside a class definition.
  A(int _a, int _b)  { 
    a = _a;
    b = _b;
  }
};

Now, if we instantiate A like this:

#include <iostream>
A* classA = new A(1,2);
int main(void)  {
  std::cout << classA.a << "\t" << classA.b << endl;
  return 0;
}

Where are classA.a and classA.b? Are they on the program stack? Are the automatically put on the heap instead, as classA is?

Not a problem in most cases, I wouldn't think, but it might be helpful to know...

3条回答
乱世女痞
2楼-- · 2019-03-05 07:01

This line is factually incorrect

  int a, b; //These are instantiated on the stack, normally

It depends on how the object is created - using new or on the stack

查看更多
我想做一个坏孩纸
3楼-- · 2019-03-05 07:09

int a, b; //These are instantiated on the stack,

No, these are not instantiated on the stack. Member variables are parts of the instance data structure, and thus are allocated in the same memory chunk as the class instance. Only if the class instance is on the stack, then the instance fields are there as well.

查看更多
Fickle 薄情
4楼-- · 2019-03-05 07:21

A class is a definition of a data structure; a block of memory. It does not define where that block of memory comes from. However, all the memory for a single object comes from the same place.

 static Class A ;

Allocates all the data for A in a stack program section.

. . . . . 
{
    Class A ;
}

Allocates ALL the data for A on the stack (or whatever mechanism used---the stack).

Class *A = new A ;

Allocates all the data for A in dynamic memory.

查看更多
登录 后发表回答