Cannot dynamic_cast void* to templated class

↘锁芯ラ 提交于 2019-12-19 04:58:34

问题


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:


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




回答2:


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.




回答3:


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/



来源:https://stackoverflow.com/questions/3155277/cannot-dynamic-cast-void-to-templated-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!