gpt4 book ai didi

c++ - 为类动态分配内存

转载 作者:行者123 更新时间:2023-11-30 03:45:06 25 4
gpt4 key购买 nike

我很清楚在 C++ 中为结构体动态分配内存。

struct Node
{
int item;
struct Node *next;
};

int main()
{
struct Node *head = new struct Node;
return 0;
}

这是一张图片。

enter image description here

堆中分配了8字节内存,head是指向它的指针。

但是当我遇到dynamically allocate memory for class时,有几个问题让我困惑了很久。有一个例子:

class Example
{
private:
int a;
double b;
public:
virtual void fun();
void fun2();
};

int main()
{
Example *e = new Example;
}

void Example::fun()
{
}

我的问题是:

1.我知道系统在堆中为int和double分配内存,系统是否也在堆中为fun()和fun2()分配内存?如果不是,哪里有 fun() 和fun2() 存储在应用程序内存中?

2.在堆中分配了多少字节?

3.指针e如何解引用函数fun()或fun2()?

4.解引用普通函数和解引用虚函数有什么区别?

最佳答案

首先,classstruct在C++中是等价的,唯一的区别是默认的访问修饰符是public类的结构和 private。而 struct Node 的数据类型只是 Node,所以 Node *head = new Node; 就足够了,不需要重复 结构无处不在。

1.I know the system allocate memory for int and double in heap,do the system also allocate memory for fun() and fun2() in heap ? if not, where are fun() and fun2() stored in application memory ?

这些方法与所有其他函数一起位于代码 block 中。该方法源代码只有一个拷贝,而不是每个实例一个。

2.How many bytes allocated in heap?

这取决于填充和对齐。 sizeof(Example) 告诉您类需要多少字节。

3.How do the pointer e dereference the function fun() or fun2()?

这取决于该方法是否为虚方法。如果不是,它就被编译成一个常规函数,除了指向 this 的指针也被传递(如果我没记错的话,在寄存器中)。

对于虚函数和#4,参见here

关于c++ - 为类动态分配内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35055967/

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