#include "boost/smart_ptr.hpp" #include #include using namespace std; #if defined(WIN32) || defined( __NT__) ostream& operator << ( ostream& strm, const string &str) { strm << str.c_str(); return strm; } #endif class Sample { public: int SomeData; Sample( int somedata=0) : SomeData(somedata) {} virtual ~Sample() = 0; }; Sample::~Sample() { } class Dad; class Child; typedef boost::shared_ptr DadPtr; typedef boost::shared_ptr ChildPtr; class Dad : public Sample { public: ChildPtr myBoy; Dad() { cout << "construction a Dad" << endl; } virtual ~Dad() { cout << "deleting a Dad" << endl; } }; class Child : public Sample { public: DadPtr myDad; Child() { cout << "construction a Child" << endl; } virtual ~Child() { cout << "deleting a Child" << endl; } }; // a "thing" that holds a smart pointer to another "thing": int main() { { DadPtr parent(new Dad); ChildPtr child(new Child); cout << "parent.use_count = " << parent.use_count() << endl; cout << "child.use_count = " << parent.use_count() << endl; // deliberately create a circular reference: parent->myBoy = child; child->myDad = parent; cout << "parent.use_count = " << parent.use_count() << endl; cout << "child.use_count = " << parent.use_count() << endl; // resetting one ptr... parent.reset(); cout << "parent.use_count = " << parent.use_count() << endl; cout << "child.use_count = " << parent.use_count() << endl; } cout << "returning to os" << endl; return 0; }