|
Boost : |
From: Peter Dimov (pdimov_at_[hidden])
Date: 2003-01-07 10:39:36
I've added a simple mark and sweep "garbage collector" to
libs/smart_ptr/sp_debug_hooks.cpp that is able to detect unreachable objects
kept alive by shared_ptr cycles. At the moment it's more a debugging aid,
and doesn't attempt to free memory, athough it is possible to extend it to
do so. This is mainly a research project; if you think that it might have a
practical use let me know. :-)
Example: (compile with -DBOOST_ENABLE_SP_DEBUG_HOOKS, link with
sp_debug_hooks.cpp)
#include <boost/shared_ptr.hpp>
#include <iostream>
struct X
{
boost::shared_ptr<X> p;
};
void report_unreachable_objects(); // in sp_debug_hooks.cpp
int main()
{
boost::shared_ptr<X> p1(new X);
boost::shared_ptr<X> p2(new X);
p1->p = p2;
p2->p = p1;
report_unreachable_objects();
std::cout << "--\n";
p1.reset();
report_unreachable_objects();
std::cout << "--\n";
p2.reset();
report_unreachable_objects();
}
Output:
C:\Documents and Settings\pdimov\My Documents\Projects\testbed>a
-- -- Unreachable object at 0x3d2c78, 12 bytes long. Unreachable object at 0x3d2cc0, 12 bytes long. -- Peter Dimov http://www.pdimov.com
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk