本地类变量位置 [英] Local class variable location

查看:51
本文介绍了本地类变量位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果在类本身在堆上实例化时,类将实例在堆栈上的所有局部变量实例化(即:堆栈上的int i; //An integerint *p; //Pointer to an int),会发生什么情况?班级成员在哪里? 这是一个示例:

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;
  }
};

现在,如果我们这样实例化A:

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;
}

classA.aclassA.b在哪里?它们在程序堆栈中吗?是像classA一样自动放置在堆上吗?

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

推荐答案

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.

这篇关于本地类变量位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆