我認爲最簡單的內存泄漏情況是動態創建一個對象,然後立即失去對它的引用。在這個簡短的例子中,您立即失去了對您創建的變量的引用,導致內存泄漏。內存泄漏在像這些小型的,人爲設計的程序中使得難以理解內存泄漏,因爲一旦程序退出,操作系統就會回收程序分配的內存。
當程序長時間運行時,問題變得嚴重。內存泄露加劇,計算機性能明顯受到阻礙。
例子:
#include <iostream>
// Object is being created, allocated on the heap then function immediately exits, losing any reference to the object. This is a memory leak
void createObject()
{
int* x = new int;
}
int prompt()
{
int response;
std::cout << "Run again?\n";
std::cin >> response;
return response;
}
int main()
{
while(continue)
{
createObject();
// Running the program again and again will exacerbate the memory leak.
continue = prompt();
}
return 0;
}
正確的方式在這個人爲的和無用的例子保留對象的引用:
int* createObject()
{
int* x = new int;
return x;
}
int main()
{
// Pointer to the object created in the function in this scope is created, so we still have access to the variable.
int* a = createObject();
return 0;
}
希望這會有所幫助,祝你好運在你的類!
請定義*「似乎不起作用」* – WhiZTiM
檢查您的進程內存。它會隨着循環而增加 –
當我觀察程序的內存使用情況時,它不會增長,因此它不會泄漏任何內存。我只是得到一個錯誤的分配錯誤。 –