我以前没有使用过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
的析构函数之前,您正在检查内存泄漏:
struct S {
S(int X = 0, int Y = 0) :x(X), y(Y) { std::cout << "built x=" << x << std::endl; }
~S() { std::cout << "destroyed x=" << x << std::endl; }
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);
_CrtDumpMemoryLeaks(); // b hasn't been destroyed yet!
}
输出:
built x=0
built x=4
built x=3
built x=2
built x=1
built x=0
["your code is leaking" dump]
destroyed x=0
destroyed x=4
destroyed x=3
destroyed x=2
destroyed x=1
destroyed x=0
b还没有被销毁,所以它没有被释放。
Just将其放入一个块中,并在该块之后检查内存泄漏:
int main()
{
{
std::unique_ptr<S> b(new S());
Bar(5, b);
}
_CrtDumpMemoryLeaks(); // b is destroyed at the end of the block
}