[vtkusers] A template to avoid calling vtkObjectBase->Delete()
de Boer Ingo
I.deBoer at polytec.de
Wed Apr 28 12:05:41 EDT 2004
Hi,
I did a similar approach based on M$ CAutoPtr class
shipped with the Visual Studio.
I guess, it is better to make it a bit more safe...
Maybe this could be a suggestion for making
vtkSmartPointer a bit safer ?
The usage is like:
CVtkPtr<vtkAxes> pvtkAxes;
pvtkAxes.Create();
pvtkAxes->SetOrigin(0, 0, 0);
and you can ask for result of create to do something
when the creation fails...
greets
Ingo
---
Dr.-Ing. Ingo H. de Boer
Polytec GmbH
Polytec-Platz 1-7, 76337 Waldbronn, Germany
phone: ++49 7243 604 106
fax : ++49 7243 604 255
#################################################################
#ifndef __CVTKPTR__
#define __CVTKPTR__
template< typename T > class CVtkPtr
{
public:
CVtkPtr() throw() : m_p( NULL )
{
}
template< typename TSrc > CVtkPtr( CVtkPtr< TSrc >& p ) throw()
{
m_p = p.Detach(); // Transfer ownership
}
template<> CVtkPtr( CVtkPtr< T >& p ) throw()
{
m_p = p.Detach(); // Transfer ownership
}
explicit CVtkPtr( T* p ) throw() : m_p( p )
{
}
~CVtkPtr() throw()
{
Free();
}
long Create() throw()
{
try
{
T *p = T::New();
if (p == NULL)
return -1; // E_OUTOFMEMORY;
Free();
m_p = p;
return S_OK;
}
catch(...)
{
return -1; // E_OUTOFMEMORY;
};
}
// Templated version to allow pBase = pDerived
template< typename TSrc > CVtkPtr< T >& operator=( CVtkPtr< TSrc >& p ) throw()
{
Free();
Attach( p.Detach() ); // Transfer ownership
return( *this );
}
template<> CVtkPtr< T >& operator=( CVtkPtr< T >& p ) throw()
{
Free();
Attach( p.Detach() ); // Transfer ownership
return( *this );
}
operator T*() const throw()
{
return( m_p );
}
T* operator->() const throw()
{
ASSERT( m_p != NULL );
return( m_p );
}
// Attach to an existing pointer (takes ownership)
void Attach( T* p ) throw()
{
ASSERT( m_p == NULL );
m_p = p;
}
// Detach the pointer (releases ownership)
T* Detach() throw()
{
T* p;
p = m_p;
m_p = NULL;
return( p );
}
// Delete the object pointed to, and set the pointer to NULL
void Free() throw()
{
if (m_p) m_p->Delete();
m_p = NULL;
}
private:
T* m_p;
};
#endif // __CVTKPTR__
More information about the vtkusers
mailing list