Possible Duplicate:
Are data members allocated in the same memory space as their objects in C++?
如果我这样声明一个对象:
void main() {
MyClass class;
}
它将在堆栈上自动创建。
如果我这样做会发生什么:
class MySecondClass {
private:
MyClass class;
}
成员会在栈上创建吗?如果是这样,如果通过 new
创建 MySecondClass
会怎样?这个成员还会在堆栈上吗?
Will the member be created on the stack?
是的。
If so, what happens if MySecondClass
is created via new
? Will this member still be on the stack?
没有。它将与对象的其余部分一起存储,“在堆上”或实现自由存储的任何位置,或者动态分配对象的任何位置(可能是某个内存池或其他东西)。
这里值得注意的是术语“堆栈”和“堆”通常被误用。您真正要问的是以下内容:
成员(member)有自动存储期限吗?有。
即使封装对象具有动态存储持续时间,它也会这样做吗?不会——封装对象的动态是,在一个意义,“继承”。
[C++11: 3.7.5]:
The storage duration of member subobjects, base class subobjects and array elements is that of their complete object (1.8).
在这两种情况下,内存中的实际位置分别是堆栈和空闲存储(“堆”),这并不重要。
而且,顺便说一下,main
必须有int
返回类型。