我正在学习 C++,对于下面的代码,如果不删除 *p,我不知道会浪费多少内存。
#include <iostream>
using namespace std;
int *getPtrToFive()
{
int *x = new int;
*x = 5;
return x;
}
int main()
{
int *p = getPtrToFive();
cout << *p << endl;
delete p; // ?????????????
}
我如何验证或证明它。我正在使用 Visual Studio 2008 Express。希望我的IDE可以立即显示结果。
干杯,
最佳答案
考虑到以下在 Debug模式下基于 Visual C++ 2010 构建的示例,它将发生 4 字节泄漏。如果发现任何泄漏,CRT 能够倾倒泄漏。 (即,不从免费存储中释放获取的资源)
#define _CRTDBG_MAP_ALLOC
#include <crtdbg.h>
int main()
{
int *rawPtr = new int(100) ;
// Purposefully not deallocating the rawPtr owned resources from free store
_CrtDumpMemoryLeaks() ;
return 0;
}
输出:
...
Detected memory leaks!
Dumping objects ->
{56} normal block at 0x006C3250, 4 bytes long.
Data: <2 > 32 00 00 00
Object dump complete.
The program '[6160] memoryLeaks.exe: Native' has exited with code 0 (0x0).
使用 std::auto_ptr
处理原始指针。如果它们超出范围,它们能够有效地重新分配拥有的资源。
例如:
void foo()
{
int *rawPtr = new int(100) ;
std::auto_ptr<int> safePtr(rawPtr) ;
// Now no need to use delete statement
} // safePtr out of scope => deallocates the resource it owned safely
// No memory leak
关于c++ - 使用 DELETE 来节省内存,有人可以证明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5477686/