views:

66

answers:

3

The exact error I'm getting is:

Cannot dynamic_cast 'object' (of type 'void*') to type 'class udDator(int)*' (source is not a pointer to a class)

This is happening inside an overridden operator delete. I'm attempting to create a templated memory management class that can inherit into any other class, managing memory through references. This would be in place of something like a smart shared_ptr, in an attempt to make memory management even more invisible, and without extra typing ( shared_ptr< someClass > shared( new someClass() ) is kinda long... ).

Anyway, here is the relevant code. If I have forgotten to mention any details, or do not have some code that you need to see, just let me know.

Overridden operator:

template< class T >
class udSharedMemory
{
public:
    void operator delete( void *object )
    {         
        T *temp = dynamic_cast< T* >( object ); //<------ ERROR!
        assert( temp && "Something went wrong during casting" );
        temp->release();
    }
}

Templated class:

template< class T >
class udDator : public udMemoryManaged, public udSharedMemory< udDator< T > >
{
// stuff
};

Usage of the templated class:

udDator< int > *test = new udDator< int >( "5" );
+1  A: 

Dynamic cast requires polymorphic behavior, which void does not have. Use a static_cast instead.

GMan
A: 

dynamic_cast can be used only with pointers and references to objects. Its purpose is to ensure that the result of the type conversion is a valid complete object of the requested class.

http://www.cplusplus.com/doc/tutorial/typecasting/

John Weldon
+2  A: 

In C++, there's no way to check whether a pointer really contains an address of an object of a given polymorphic type.

You need to have a pointer to one of the bases. For example, derive all relevant objects from one polymorphic interface, take the void pointer, cast it to that interface, and from there you will be able to dynamically cast it to the type you need to perform the run-time check.

Pavel Radzivilovsky
This is some very good information, thank you for posting this. I will take it into consideration. However, I will be flagging another answer, as it is technically the direct solution to my posted problem. I wish I could set your solution as the answer too...
Freezerburn