gpt4 book ai didi

c++ - 成员变量驻留在哪个内存段?

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:56:00 24 4
gpt4 key购买 nike

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

最佳答案

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

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

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

静态存储是使用 staticextern 或在命名空间范围内声明的结果,通常由数据段(例如 css、bss 或 data)实现,位于编译器的自由裁量权。

constexpr 对象存在异常,如果从未使用过该对象的地址,则该对象可能只存在于编译时,没有任何分配的空间。

关于c++ - 成员变量驻留在哪个内存段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18949762/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com