[英]Is this proper use of dynamic_cast?
I have three classes: Generic, CFG, and Evaluator. 我有三类:通用,CFG和评估器。
Here's Generic: 这是通用的:
class Generic: public virtual Evaluator, public CFG, public LCDInterface {
Here's CFG: 这是CFG:
class CFG : public virtual Evaluator {
And Evaluator subclasses nothing. 评估者没有任何子类化。
I'm providing a DLL named PluginLCD, and it has a method called Connect: 我提供了一个名为PluginLCD的DLL,它具有一种称为Connect的方法:
void PluginLCD::Connect(Evaluator *visitor) {
visitor_ = dynamic_cast<Generic *>(visitor);
if(!visitor_)
return;
type_ = visitor_->GetType();
}
Here's how I'm compiling the DLL through scons: 这是我通过scons编译DLL的方法:
env.SharedLibrary(['PluginLCD.cpp', 'Evaluator.cpp', 'Generic.cpp', 'CFG.cpp'])
Now, there are two scenarios in my code. 现在,我的代码中有两种情况。 One is in class LCDControl
, which subclasses CFG
. 一种是LCDControl
类,它是CFG
子类。 The other scenario is above where Generic
subclasses Evaluator
and CFG
. 上面的另一个场景是Generic
子类Evaluator
和CFG
。 Evaluator has a method called LoadPlugins, which does what its name suggests, passing this
through to the DLL via method Connect
. 评价者有一个名为LoadPlugins方法,它做什么它的名字一样,通过this
通经法DLL Connect
。 Well, in the first scenario the cast to Generic *
in Connect should return NULL
. 好吧,在第一种情况下,在Connect中对Generic *
的强制转换应返回NULL
。 However, in the second scenario, as far as I know, a valid pointer should be returned. 但是,据我所知,在第二种情况下,应该返回一个有效的指针。 It doesn't seem to be happening this way. 它似乎并非以这种方式发生。 Am I wrong about this? 我对此有错吗?
dynamic_cast is known to break across module boundaries with many compilers (including MSVC and gcc). 众所周知,dynamic_cast打破了许多编译器(包括MSVC和gcc)的模块界限。 I don't know exactly why that is, but googling for it yields many hits. 我不知道为什么会这样,但是使用谷歌搜索会产生很多成功。 I'd recommend trying to get rid of the dynamic_cast in the first place instead of trying to find out why it returns null in your second scenario. 我建议首先尝试摆脱dynamic_cast,而不要尝试找出为什么在第二种情况下它返回null的原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.