我有以下 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”对其进行初始化)吗?
最佳答案
x
是 A
的成员。它是每个 A
对象的物理部分,类似于您的 ARM 在物理上是您的一部分。因此,无论 A
对象在栈上、堆上还是在其他任何地方,它的 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++ 指针对象位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30704356/