2

我很想知道初始化的成员变量在内存中的位置?即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
}
4

2 回答 2

1

类类型的对象的分配方式与int其他类型的对象相同。非静态类成员分配在包含对象内部。

本地对象默认具有按照标准的“自动存储”,由通常称为堆栈的运行环境的一部分来实现。对象是否或如何显式初始化并不重要。

Usingnew根据标准从“空闲存储”分配内存,其实现也称为堆。

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

对象存在一个例外constexpr,如果没有使用对象的地址,它可能只存在于编译时而没有任何分配的空间。

于 2013-09-23T00:11:04.173 回答
0

It's the same as any other variable. It's not really specified in the standard, but if you create a local class instance it'll generally reside on the stack, and if you new it, it'll reside in the free store. The member variables are just inside the instance as you'd expect. Static class variables will likely reside in one of the data segments.

Non-static instances don't reside anywhere "after compilation", they get created at run time.

于 2013-09-22T23:25:52.927 回答