无法将 void* 动态转换为模板类
我得到的确切错误是:
Cannotdynamic_cast 'object' (of type 'void*') to type 'class udDator(int)*' (源不是指向类的指针)
这发生在重写的运算符删除内部。我正在尝试创建一个模板化内存管理类,它可以继承到任何其他类,通过引用管理内存。这将取代诸如智能shared_ptr之类的东西,试图使内存管理更加不可见,并且无需额外输入(shared_ptr
无论如何,这是相关的代码。如果我忘记提及任何细节,或者没有您需要查看的代码,请告诉我。
重写运算符:
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();
}
}
模板化类:
template< class T >
class udDator : public udMemoryManaged, public udSharedMemory< udDator< T > >
{
// stuff
};
模板化类的用法:
udDator< int > *test = new udDator< int >( "5" );
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" );
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在 C++ 中,无法检查指针是否确实包含给定多态类型的对象的地址。
您需要有一个指向其中一个基数的指针。例如,从一个多态接口派生所有相关对象,获取 void 指针,将其强制转换为该接口,然后从那里您将能够将其动态强制转换为执行运行时检查所需的类型。
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.
动态转换需要多态行为,而
void
不具备这种行为。请改用static_cast
。Dynamic cast requires polymorphic behavior, which
void
does not have. Use astatic_cast
instead.http://www.cplusplus.com/doc/tutorial/typecasting/
http://www.cplusplus.com/doc/tutorial/typecasting/