我认为最简单的内存泄漏情况是动态创建一个对象,然后立即失去对它的引用。在这个简短的例子中,您立即失去了对您创建的变量的引用,导致内存泄漏。内存泄漏在像这些小型的,人为设计的程序中使得难以理解内存泄漏,因为一旦程序退出,操作系统就会回收程序分配的内存。
当程序长时间运行时,问题变得严重。内存泄露加剧,计算机性能明显受到阻碍。
例子:
#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
检查您的进程内存。它会随着循环而增加 –
当我观察程序的内存使用情况时,它不会增长,因此它不会泄漏任何内存。我只是得到一个错误的分配错误。 –