我有一个关于 C++ 中的内存管理的问题。据我所知,Java 中不需要释放内存,因为未使用的对象会在某个时候被 JVM 垃圾收集器删除。我的意思是,如果我在C++中忘记释放内存,使用的内存地址会被占用,直到我重新启动机器并且内存中的数据丢失?例如,在下面的代码中,我有一个简单的链表,您可以观察到我没有释放内存(在析构函数中进行了注释):
#include <iostream>
using namespace std;
typedef struct Node{
Node* next;
int id;
} *ListPtr;
class LinkedList{
public:`ListPtr header;
LinkedList(){
header = NULL;
}
~LinkedList(){
/*
ListPtr a = header,b;
while(a != NULL)
{
b = a;
a = a -> next;
delete b;
}
delete a,b;
cout << "Memory freed!"<< endl;
*/
}
public: void Insert(){
ListPtr new_element = new Node;
new_element -> next = NULL;
if(header == NULL){
header = new_element;
header -> …Run Code Online (Sandbox Code Playgroud)