christopher diggins wrote:[color=blue]
> I posted to my blog a special pointer class work-around for[/color]
inheriting from[color=blue]
> base classes without virtual destructors. I was wondering if there is[/color]
any[color=blue]
> other similar work, and whether there are any problems with my[/color]
proposed[color=blue]
> approach. Thanks in advance!
> See
http://www.artima.com/weblogs/viewpo...?thread=107587
>
> For those who just want the code:
>
> template<typename target_type>
> class base_class_ptr {
> public:
> // forward declarations
> template <class T>
> struct functions;
> template <class T>
> base_class_ptr(T* x)
> : m_a(x), m_t(&functions<T>::table)
> {}
> target_type* operator->() {
> return static_cast<target_type*>(m_a);
> }
> void Delete() {
> m_t->Delete(m_a);
> m_a = NULL;
> }
> // Function table type
> struct table {
> void (*Delete)(void*);
> };
> // For a given referenced type T, generates functions for the
> // function table and a static instance of the table.
> template<class T>
> struct functions
> {
> static typename base_class_ptr<target_type>::table table;
> static void Delete(void* p) {
> delete static_cast<T*>(p);
> }
> };
> private:
> void* m_a;
> table* m_t;
> };
>
> template<typename target_T>
> template<class T>
> typename base_class_ptr<target_T>::table
> base_class_ptr<target_T>::functions<T>::table = {
> &base_class_ptr<target_T>::template functions<T>::Delete
> };
>
> --
> Christopher Diggins
> Object Oriented Template Library (OOTL)
>
http://www.ootl.org[/color]
I would avoid using void.
The following class is a safer workaround method, and it's type safe.
template<typename base_type>
class base_class_ptr
{
class BaseContainer{
public:
virtual ~BaseContainer(){}
};
template<typename derive_type>
class Container : public BaseContainer{
derive_type *m_derive_ptr;
public:
Container(derive_type* derive_obj):m_derive_ptr(derive_obj){}
~Container(){delete m_derive_ptr;}
};
public:
template<typename derive_type>
base_class_ptr(derive_type* derive_obj)
:m_base_ptr(derive_obj), m_BaseContainer(new
Container<derive_type>(derive_obj)){}
~base_class_ptr(){delete m_BaseContainer;}
base_type* operator->() {return m_base_ptr;}
private:
base_type *m_base_ptr;
BaseContainer *m_BaseContainer;
};
Example usage:
void SomeFunction()
{
base_class_ptr<MyBaseClass> ptr_a(new MyDerivedClass_a);
ptr_a->TestFunct();
base_class_ptr<MyBaseClass> ptr_b(new MyDerivedClass_b);
ptr_b->TestFunct();
}