【发布时间】:2014-12-21 17:01:47
【问题描述】:
我之前没有使用过std::unique_ptr,所以这是我第一次尝试在递归调用中使用它,如下所示:
#define CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
#include <memory>
struct S {
S(int X = 0, int Y = 0):x(X), y(Y) {}
int x;
int y;
std::unique_ptr<S> p;
};
void Bar(int i, std::unique_ptr<S> &sp)
{
i--;
sp->p = std::unique_ptr<S>(new S(i, 0));
if (i > 0)
Bar(i, sp->p);
}
int main()
{
std::unique_ptr<S> b (new S());
Bar(5, b);
// Detects memory leaks
_CrtDumpMemoryLeaks();
}
在程序结束时。我发现我分配的任何内存都没有根据在 Windows 8 x64 上运行的 Visual C++ 2012 x86 中的_CrtDumpMemoryLeaks(); 释放。
【问题讨论】:
-
b在您调用该内存泄漏函数时仍然存在。 -
只是
b的析构函数在超出范围之前不会运行,即在您调用_CrtDumpMemoryLeaks()之后。 -
啊,我将
b移到了一个全新的函数中,并且做对了。
标签: c++ c++11 recursion memory-leaks unique-ptr