www.pudn.com > 3D_Tank.rar > ComPtr.h
#pragma once #include/////////////////////////////////// // CComPtr /////////////////////////////////// template class CComPtr { public: explicit CComPtr(T *pInterface = 0) throw() : m_pInterface( pInterface ) {} CComPtr(const CComPtr &ptrRight) throw() : m_pInterface( ptrRight.Get() ) { AddRef(); } template CComPtr(const CComPtr &ptrRight) throw() : m_pInterface( ptrRight.Get() ) { AddRef(); } ~CComPtr() { Release(); } T* operator ->() const throw() { assert( m_pInterface ); return m_pInterface; } T* Get() const throw() { return m_pInterface; } bool Empty() const throw() { return m_pInterface == 0; } void Reset(T *pInterface = 0) throw() { Assign( pInterface ); } template CComPtr & operator =(const CComPtr &ptrRight) throw() { if( Assign( ptrRight.Get() ) ) AddRef(); return *this; } CComPtr & operator =(const CComPtr &ptrRight) throw() { if( Assign( ptrRight.Get() ) ) AddRef(); return *this; } private: template friend CComPtr static_cast_comptr(const CComPtr &ptr); void AddRef() { if( m_pInterface ) m_pInterface->AddRef(); } void Release() { if( m_pInterface ) m_pInterface->Release(); } bool Assign(T *pInterface) { if( m_pInterface != pInterface ) { Release(); m_pInterface = pInterface; return true; } else return false; } private: T *m_pInterface; }; /////////////////////////////////// // Helper function /////////////////////////////////// template CComPtr static_cast_comptr(const CComPtr &ptr) { if( ptr.m_pInterface ) ptr->AddRef(); return CComPtr ( static_cast ( ptr.m_pInterface ) ); }