我有一個關於C++內存管理的問題。據我所知,沒有必要在Java中取消分配內存,因爲未使用的對象有時會被JVM垃圾回收器清除。我的觀點是,如果我忘記使用C++釋放內存,那麼在我重新啓動機器並且內存中的數據丟失之前,已使用的內存地址將被佔用?例如,在下面的代碼我有一個簡單的鏈表,你可以看到,我不釋放內存(在析構函數評論):如果我忘記釋放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 -> id = 0;
}
else{
new_element -> next = header;
new_element -> id = header -> id + 1;
header = new_element;
}
}
public: void Print(){
ListPtr curr = header;
while(curr != NULL){
cout << "[" << &curr -> id << "]" << "-->";
curr = curr -> next;
}
cout << "[NULL]"<<endl;
}};
int main(){
LinkedList list;
list.Insert();
list.Insert();
list.Insert();
list.Insert();
list.Insert();
list.Print();
return 0;
}
這是否意味着那些內存地址將被佔用,直到我關機了?程序執行完成後,變量(如整數)會發生什麼情況?我可以釋放他們嗎?
本方案的輸出是: [0x8622ac] - > [0x86229c] - > [0x86228c] - > [0x86227c] - > [0x8615bc] - > [NULL]
[當你在malloc之後沒有自由時真的會發生什麼?](http://stackoverflow.com/questions/654754/what-really-happens-when-you-dont-free-after-malloc ) –
如果您使用標準容器開始 - 例如'std :: string','std :: vector','std :: set' - 如果你通過「value」存儲元素,他們會自動管理和釋放內存。當你必須使用指針來跟蹤或以其他方式處理元素時,首選「智能指針」,它可以執行所有權/生命週期模型並避免泄漏:特別是,C++ 11標準庫提供'std :: unique_ptr'和'std :: shared_ptr'這非常有用。 –