C++ 指针对象位置
C++ Pointer Object Location
我有以下 C++ 代码:
struct B {
int c;
int d;
}
struct A {
int a;
B x;
}
int main() {
A * ptr = new A;
ptr->a = 1;
ptr->x.c = 2;
ptr->x.d = 23;
// a lot of lines of codes later ...
// Will the following values be guranteed?
cout << ptr->x.c << endl;
cout << ptr->x.d << endl;
}
在堆上声明一个新的 "struct A" 之后,ptr->x 是在栈上还是在堆上声明?如果我想让 x 在堆上,我必须将 属性 x 声明为指针(因此,用 "new" 初始化它)吗?
ptr->x
将在堆上。
这是因为当您创建 A
的实例时,它将为其所有成员分配足够的内存。其中包括 B
.
类型的成员
x
是 A
的成员。它是每个 A
object 身体的一部分,就像你的手臂是你身体的一部分一样。因此,无论 A
object 在栈上、堆上还是在其他任何地方,它的 x
成员就在那里。所以回答这个问题:
If i want x to be on the heap, must i declare property x as a pointer (and hence, initialize it with "new") ?
没有。如果拥有它的 A
在堆上,它将在堆上。
我有以下 C++ 代码:
struct B {
int c;
int d;
}
struct A {
int a;
B x;
}
int main() {
A * ptr = new A;
ptr->a = 1;
ptr->x.c = 2;
ptr->x.d = 23;
// a lot of lines of codes later ...
// Will the following values be guranteed?
cout << ptr->x.c << endl;
cout << ptr->x.d << endl;
}
在堆上声明一个新的 "struct A" 之后,ptr->x 是在栈上还是在堆上声明?如果我想让 x 在堆上,我必须将 属性 x 声明为指针(因此,用 "new" 初始化它)吗?
ptr->x
将在堆上。
这是因为当您创建 A
的实例时,它将为其所有成员分配足够的内存。其中包括 B
.
x
是 A
的成员。它是每个 A
object 身体的一部分,就像你的手臂是你身体的一部分一样。因此,无论 A
object 在栈上、堆上还是在其他任何地方,它的 x
成员就在那里。所以回答这个问题:
If i want x to be on the heap, must i declare property x as a pointer (and hence, initialize it with "new") ?
没有。如果拥有它的 A
在堆上,它将在堆上。