memory lost using cyclic pointers (shared_ptr)
Hi,
I think that it is expected that shared_ptr cannot handle points that
have cyclic references. In the following example, "a" points to "b"
and "b" points to "a". There is a memory leak. I then modified it to
remove the dependence using bare pointers, then the leak is resolved.
But this is not a very satisfactory solution, as the programmer has to
know whether to use bare point or shared_ptr. For very complexity
program, it may not be possible to figure out it correctly.
Does anybody know what is the best strategy for handing cyclic pointers?
~/linux/test/cpp/library/std/tr1/shared_ptr/loop$ cat main.cpp
#include
I think that it is expected that shared_ptr cannot handle points that have cyclic references. In the following example, "a" points to "b" and "b" points to "a". There is a memory leak. I then modified it to remove the dependence using bare pointers, then the leak is resolved. But this is not a very satisfactory solution, as the programmer has to know whether to use bare point or shared_ptr. For very complexity program, it may not be possible to figure out it correctly.
Does anybody know what is the best strategy for handing cyclic pointers?
On of the directions should use weak_ptr.
On Fri, Sep 9, 2011 at 4:13 AM, Max Vasin
2011/9/9 Igor R
: On of the directions should use weak_ptr. The question was what to do if these directions are very hard figure out correctly. Conservative GC can be a semi-solution leaks will still remain but programming will be much simpler.
One could imagine a scenario in which you define your cross-linked data structure to the Boost Graph Library as a graph. When it's time to free your whole structure, you run a graph-traversal algorithm to identify cycles, then manually reset() specific shared_ptr instances... But if there's a well-defined time at which you want to free your whole linked structure, it would be simpler to put all nodes into a memory pool that can be freed in one swell foop. If your data structure is sufficiently similar across runs, you might build it, run graph traversal as described above to identify cycles, analyze those cycles and decide where to change shared_ptr to weak_ptr for future runs. But that tactic wouldn't work if the data structure varies wildly with different input data.
participants (4)
-
Igor R
-
Max Vasin
-
Nat Linden
-
Peng Yu