成员变量驻留在哪个内存段中?

时间:2013-09-22 23:22:17

标签: c++ variables initialization

我很想知道初始化成员变量在内存中的位置?即,css,bss,数据段,堆......

如果我的问题很愚蠢,请不要骂我:) 例如

class A
{
    A();
    int m_iVar;
}

A::A(int i)
{
    m_iVar = i;
}

A::A()
{
    m_iVar = 99;
}

main()
{
    A o; // => After compilation, the object o, in which segment does it reside? and especially  where does "m_iVar" reside
    A o1(5); // => After compilation here object o1, in which segment does it reside?and especially where does "m_iVar" reside?

    A *pA = new A; // After compilation, here the memory pointed by pA, I guess it goes to heap, but the variable "m_iVar" where does it reside
}

2 个答案:

答案 0 :(得分:0)

它与任何其他变量相同。它并没有在标准中真正指定,但如果你创建一个本地类实例,它通常会驻留在堆栈上,如果你new它,它将驻留在免费商店中。成员变量就像您期望的那样位于实例内部。静态类变量可能驻留在其中一个数据段中。

非静态实例不会驻留在“编译后”的任何位置,它们会在运行时创建。

答案 1 :(得分:0)

类类型的对象与int的对象或任何其他类型的对象分配相同。非静态类成员在包含对象内分配。

默认情况下,本地对象根据标准具有“自动存储”,该标准由通常称为堆栈的操作环境的一部分实现。是否或如何显式初始化对象无关紧要。

使用new根据标准从“免费存储”中分配内存,其实现也称为堆。

静态存储由使用staticextern或在命名空间范围内的声明产生,通常由数据段(如css,bss或data)实现,由编译器自行决定。

constexpr个对象存在异常,如果没有使用该对象的地址,它可能只在编译时存在且没有分配空间。