检查交叉转换是否可能工作? [英] Checking whether a cross-cast could possibly work?
问题描述
我知道使用 dynamic_cast
在类层次结构中执行交叉是合法的。例如,如果我有类如下所示的类:
I know that it's legal to use dynamic_cast
to do a "cross-cast" across a class hierarchy. For example, if I have classes that look like this:
A B
\ /
C
如果我有一个 A *
在 C
类型的对象处,我可以使用
If I have an A*
pointer that's pointing at an object of type C
, then I can use
A* aPtr = /* ... something that produces a C* ... */
B* bPtr = dynamic_cast<B*>(aPtr);
以获取指向 B
C
的对象。
我提到这个的原因是,编写上面的代码,可能编译器还没有看到 C
的定义,即使看到 A
B
。这意味着编译器可能没有检测到 A
和 B
之间的任何类型的连接,但它仍然无论如何编译代码,因为有可能存在 C
类,并且在某些情况下 dynamic_cast
。
The reason I mention this is that at the time that I write the above code, it's possible that the compiler has not yet seen the definition of C
even though it's seen A
and B
. This means that it's possible that the compiler does not detect any sort of connection between A
and B
, but it still has to compile the code anyway because it's possible for a class like C
to exist and for the dynamic_cast
to succeed under some circumstance.
问题是,这意味着我可以不小心地交叉到一个错误类型的对象。假设我有类似这样的类:
The problem is that this means that I can accidentally cross-cast to an object of the wrong type. Suppose that I have classes that look like this:
A B D
\ /
C
这里, D
是一些随机无关的类。如果我尝试写这样的:
Here, D
is some random unrelated class. If I try writing something like this:
A* aPtr = /* ... get a C* pointer ... */
D* dPtr = dynamic_cast<D*>(aPtr);
然后,这个 dynamic_cast
,因为没有可能的方法连接 A
和 D
。如果我使用 D
意外,因为我打算使用 B
,编译器会给我没有任何迹象表明,有一个无意义的转换。
Then this dynamic_cast
will always fail at runtime, since there's no possible way to connect A
and D
. If I'm using D
accidentally because I meant to use B
, the compiler will give me no indication whatsoever that I have a meaningless cast.
我的问题是:有一些方法,我可以让编译器警告我,运行时总是会失败? / strong>我会很高兴与语言级解决方案或一些编译器设置任何主要的编译器,可以检测到这一点。如果有一个外部工具,这也很好;我只想知道是否可以捕获这类错误。
My question is: is there some way that I can get the compiler to warn me that the cast will always fail at runtime? I'd be happy with a language-level solution or some compiler setting for any major compiler that could detect this. If there's an external tool, that's fine as well; I just want to know if it's possible to catch this class of errors.
推荐答案
这是不可能在编译时检测到。引入关系的类 C
可以在尚未编写的动态可加载库中找到,而编译器无法证明。
It's not possible to detect this at compile-time. The class C
that introduces the relationship could be found in a dynamically loadable library that hasn't even been written yet, and the compiler can't prove otherwise.
可能有一些例外。如果 A
只有私有构造函数(或私有析构函数),那么编译器可以确定没有新的子类不会被命名为朋友 A
。
There may be a few exceptions though. If A
has only private constructors (or a private destructor) then the compiler can be certain that there will be no new subclasses that aren't named as friends by A
.
这篇关于检查交叉转换是否可能工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!