Local class variable location

2019-03-05 07:07发布

问题:

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

回答1:

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.



回答2:

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:

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.