I wrote a smart pointer class, although I eventually decided not to bother using it. But it was this:
template <class Type> class pointer{ public: pointer ( ) { m_Object = NULL; } pointer ( Type* Object ) { m_Object = Object; if( m_Object ) m_Object->AddRef( (object**)&m_Object ); } ~pointer ( ) { if( m_Object ) m_Object->Release( ); } inline operator = ( Type* Object ) { if( m_Object ) m_Object->Release( ); m_Object = Object; if( m_Object ) m_Object->AddRef( (object**)&m_Object ); } inline Type* operator -> ( ) const { return m_Object; } inline Type* operator () ( ) const { return m_Object; } inline operator Type* ( ) const { return m_Object; } inline bool operator == ( Type* Object ) const { return m_Object == Object; } inline bool operator != ( Type* Object ) const { return m_Object != Object; } inline operator bool ( ) const { return m_Object ? true : false; } private: Type* m_Object;};
The object had to be derived from a base object that had the AddRef and Release methods. All my classes are derived from a common base class (except pointer) so I could do things like this.
It would be used like this:
pointer<OpenGL> pGL = new OpenGL; // Create it.pGL->SetDisplayMode( 640, 480, 16 ); // Do something.pGL = NULL; // This releases the object.
~CGameProgrammer( );