Sunday, 15 March 2015

c++ - Memory leaks with recursive function using std::unique_ptr -



c++ - Memory leaks with recursive function using std::unique_ptr -

i haven't used std::unique_ptr before, kind of first effort trying utilize in recursion phone call following:

#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(); }

at end of program. find whatever memory allocated wasn't freed according _crtdumpmemoryleaks(); in visual c++ 2012 x86 running on windows 8 x64.

everything destroyed correctly @ end of proper scopes you're checking memory leaks before destructor b gets called:

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! }

output:

built x=0 built x=4 built x=3 built x=2 built x=1 built x=0 ["your code leaking" dump] destroyed x=0 destroyed x=4 destroyed x=3 destroyed x=2 destroyed x=1 destroyed x=0

c++ c++11 recursion memory-leaks unique-ptr

No comments:

Post a Comment