具有多重继承的强制转换
如果您有一个指向从 BaseA
和 BaseB
继承的派生类的 void* 指针,编译器如何将 void*
指针强制转换为 < code>BaseA*(或 BaseB*
)而不知道 void*
指针的类型为 Derived
?
If you have a void* pointer to Derived class that inherits from both BaseA
and BaseB
, how does the compiler cast the void*
pointer to BaseA*
(or BaseB*
) without knowing that the void*
pointer is of type Derived
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
事实并非如此。使用
static_cast
与void*
进行转换时的唯一保证是:例如,以下代码是不正确的,因为
void*
被强制转换为原始指针类型以外的类型(强制转换顺序为B1*
->void*
->B2*
):尝试在此处使用
b2ptr
会导致未定义的行为。唯一可以安全地将voidptr
转换为的类型是B1*
,因为这是从中获取void*
的类型(好吧,或char*
,因为任何内容都可以通过char*
访问)。It doesn't. The only guarantee when casting to and from a
void*
using astatic_cast
is:For example, the following code is incorrect because the
void*
is cast to a type other than the original pointer type (the cast sequence isB1*
->void*
->B2*
):Attempting to use
b2ptr
here would result in undefined behavior. The only type to which you can safely castvoidptr
isB1*
, since that is the type from which thevoid*
was obtained (well, or to achar*
, since anything can be accessed via achar*
).编译器不会将
void*
指针强制转换为任何内容,而您(程序员)则可以这样做。为了使用
void*
指针执行任何有用的操作,您需要显式将其转换为非void*
指针,并且如果您如果指针实际指向的类型是错误的,则您输入“未定义行为城市”。The compiler doesn't cast the
void*
pointer to anything -- you, the programmer, do.In order to do anything useful with a
void*
pointer, you need to explicitly cast it to a non-void*
pointer, and if you're wrong about what type the pointer actually points to, you enter Undefined Behavior City.