gpt4 book ai didi

c++ - 新建和删除如何工作以及它们存储在哪里?

转载 作者:太空宇宙 更新时间:2023-11-04 16:10:44 24 4
gpt4 key购买 nike

我定义了一个名为 Node 的结构。

现在,我做:

Node* temp;
temp = new Node();

temp是一个指向Node的指针,Node本身就是一个复杂的数据类型。

Question-1: Is memory allocation on heap contiguous?

Question-2: Which block of memory on heap does 'temp' exactly point to? Is it the memory address of the very first data member in the struct Node?

现在,我做:

delete temp;

Question-3: This deallocates the memory. So, does temp point to a garbage value now or does it point to NULL?

最佳答案

Question-1: Is memory allocation on heap contiguous?

是的,你得到了一个连续的 block 。这并不一定意味着两次连续的分配会给你连续的 block 。

Question-2: Which block of memory on heap does 'temp' exactly point to? Is it the memory address of the very first data member in the struct Node?

不一定,取决于 Node 的定义方式以及您的平台和编译器的 ABI 是什么。

Question-3: This deallocates the memory. So, does temp point to a garbage value now or does it point to NULL?

是的,它一直指向同一个地址(现在是免费的,最终可能会重新分配),您可以将其设置为 NULL。


对于问题 2。让我们来做个小实验:

1) 普通结构

#include <iostream>

class A {
public:
int a;
};

int main() {

A *b=new A();

std::cout << std::hex << b << std::endl;
std::cout << std::hex << &(b->a) << std::endl;
}

和结果(用cygwin编译)

0x800102d0
0x800102d0

所以在这种情况下我们没问题。

2)继承

#include <iostream>

class A {
public:
int a;
};

class B: public A {
public:
int b;
};

int main() {

B *b=new B();

std::cout << std::hex << b << std::endl;
std::cout << std::hex << &(b->b) << std::endl;
std::cout << std::hex << &(b->a) << std::endl;
}

结果:

0x800102d0
0x800102d4
0x800102d0

所以,B*不再是指向B首元素的指针,而是指向A首元素的指针。

3)虚拟类

#include <iostream>

class A {
public:
virtual ~A() { }
int a;
};

class B: public A {
public:
int b;
};

int main() {

B *b=new B();

std::cout << std::hex << b << std::endl;
std::cout << std::hex << &(b->b) << std::endl;
std::cout << std::hex << &(b->a) << std::endl;

}

结果

0x800102d0
0x800102d8
0x800102d4

现在指针既不指向 A 的第一个元素,也不指向第一个元素B 的元素,但到控制结构。

关于c++ - 新建和删除如何工作以及它们存储在哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28979464/

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