使用多重继承时,何时静态转换安全? [英] When is static cast safe when you are using multiple inheritance?
问题描述
我发现自己处在某种类型的情况下。类型是三个(或更多)继承级别之一。我调用了返回 B *
的工厂,但是T是类型的最高级别(如果我的代码知道它是什么)或第二级别。
I found myself in a situation where I know what type something is. The Type is one of three (or more) levels of inheritance. I call factory which returns B*
however T is either the highest level of a type (if my code knows what it is) or the 2nd level.
无论如何,我在模板中做了 static_cast
,这是错误的做法。我的问题是,何时可以安全地进行静态投射?有没有这样的时间?我之所以这样做,是因为当我不小心将T当作怪异的东西(发生了)而动态转换忽略(并返回null)时,我宁愿遇到编译错误。但是,当我知道正确的类型时,指针将无法调整,从而导致指针指向错误。我不确定为什么在这种情况下根本不允许使用静态投射。
Anyways, I did a static_cast
in the template which is the wrong thing to do. My question is WHEN can I static cast safely? Is there ever such a time? I did it in this case because I'd rather get compile errors when I accidentally have T as something wacky which (has happened and) dynamic cast ignores (and returns null). However when I know the correct type the pointer is not adjusted causing me to have a bad pointer. I'm not sure why static cast is allowed in this case at all.
何时可以使用static_cast安全地向下投射?有没有情况?现在,使用 static_cast
似乎总是错误的(当目的是降低演员阵容时)
When can I use static_cast for down casting safely? Is there ever a situation? Now it seems like it always is wrong to use a static_cast
(when the purpose is to down cast)
好我想出了如何重现它。
Ok I figured out how to reproduce it.
#include <iostream>
struct B { virtual void f1(){} };
struct D1 : B {int a;};
struct D2 : B {int a, b; };
struct DD : D1, D2 {};
int main(){
void* cptr = new DD(); //i pass it through a C interface :(
B* a = (B*)cptr;
D2* b = static_cast<D2*>(a); //incorrect ptr
D2* c = dynamic_cast<D2*>(a); //correct ptr
std::cout << a << " " <<b << " " <<c;
}
推荐答案
A交叉广播:
struct Base1 { virtual void f1(); };
struct Base2 { virtual void f2(); };
struct Derived : Base1, Base2 {};
Base1* b1 = new Derived();
Base2* b2 = dynamic_cast<Base2*>(b1);
需要使用 dynamic_cast
, static_cast
无法完成( static_cast
应该会导致编译时错误。) dynamic_cast
如果任一基类都不是多态的(虚拟函数的存在不是可选的),也会失败。
requires use of dynamic_cast
, it cannot be done with static_cast
(static_cast
should have caused a compile-time error). dynamic_cast
will also fail if either base class is not polymorphic (the presence of virtual functions is NOT optional).
请参见此解释MSDN上的
这篇关于使用多重继承时,何时静态转换安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!