C++ 指针对象位置

标签 c++ heap-memory stack-memory

我有以下 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”对其进行初始化)吗?

最佳答案

xA 的成员。它是每个 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/

相关文章:

c - 为什么我要 free() 一个由 malloc() 分配的对象?

c++ - 对 C++ 堆分配器和 STL 进行碎片整理

java - Android 堆 1 字节数组类型非常大

c++ - 数组作为模板参数 : stack or heap?

C变量分配时间和空间

c++ - 添加无符号偏移量

c++ - 为什么成员 `float x` 在 main() 中为对象 `0.` 和 `a` 初始化为 `b`?

c++ - 无效的指针转换 C++

c++ - 带指针的顶级 const

c++ - 我的栈内存空间膨胀了吗?