#include #include #ifdef _MSC_VER #pragma warning( disable: 4355 ) #endif class u_list { public: /* Create a list that only contains itself. */ u_list( ) : m_prev( this ) , m_next( this ) { } /* Swap the position of the "list" and "this" list.*/ inline void swap( u_list *list ) { u_list temp; this->attach( &temp ); this->detach( ); list->attach( this ); list->detach( ); temp.attach( list ); temp.detach( ); } inline bool is_one_node_only( ) const { return m_next == this; } /* Detach myself from this link list. */ inline void detach( ) { attach_or_detach( this->m_next ); } /* Join the "list" and "this" list. */ inline void attach( u_list *list ) { attach_or_detach( list ); } protected: inline void attach_or_detach( u_list *list ) { u_list *prev1 = this->m_prev; u_list *prev2 = list->m_prev; prev1->m_next = list; prev2->m_next = this; this->m_prev = prev2; list->m_prev = prev1; } u_list *m_prev; u_list *m_next; }; template< class T > class u_shared_ptr { public: ~u_shared_ptr( ) { bool is_one_node_only = list.is_one_node_only( ); /* Detach myself from ptr list. */ list.detach( ); if ( is_one_node_only ) { if ( m_object != NULL ) { printf("delete\n"); delete m_object; } } } explicit u_shared_ptr( T *object ) : m_object( object ) { } u_shared_ptr( u_shared_ptr const &ptr ) : m_object( ptr.m_object ) { list.attach (const_cast< u_list * >( &ptr.list )); } u_shared_ptr &operator=( u_shared_ptr const &ptr ) { u_shared_ptr( ptr ).swap( *this ); return *this; } protected: inline void swap( u_shared_ptr &ptr ) { std::swap( m_object, ptr.m_object ); list.swap( &ptr.list ); } T *m_object; u_list list; }; struct test { test( ) { printf( "In construction of test\n" ); } ~test( ) { printf( "In destruction of test\n" ); } }; int main( ) { u_shared_ptr p( new test ); u_shared_ptr p1 = p; u_shared_ptr p2( new test ); p2 = p1; p2 = p; p2 = p1; p1 = p = p2; u_shared_ptr p3(p1); u_shared_ptr p4 = p1; return 0; }