具有多重继承的强制转换

发布于 2024-09-11 19:05:34 字数 202 浏览 1 评论 0原文

如果您有一个指向从 BaseABaseB 继承的派生类的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

装纯掩盖桑 2024-09-18 19:05:36

事实并非如此。使用 static_castvoid* 进行转换时的唯一保证是:

指向对象的指针类型值转换为“指向 cv void”的指针并返回到原始指针类型将具有其原始值 (C++03 §5.2.9/10)。

例如,以下代码是不正确的,因为 void* 被强制转换为原始指针类型以外的类型(强制转换顺序为 B1* -> void* -> B2*):

struct B1 { int i; };
struct B2 { int j; };

struct D : B1, B2 { };

D x;
B1*   b1ptr   = &x;
void* voidptr = b1ptr;
B2*   b2ptr   = static_cast<B2*>(voidptr);

尝试在此处使用 b2ptr 会导致未定义的行为。唯一可以安全地将 voidptr 转换为的类型是 B1*,因为这是从中获取 void* 的类型(好吧,或 char*,因为任何内容都可以通过 char* 访问)。

It doesn't. The only guarantee when casting to and from a void* using a static_cast is:

A value of type pointer to object converted to "pointer to cv void" and back to the original pointer type will have its original value (C++03 §5.2.9/10).

For example, the following code is incorrect because the void* is cast to a type other than the original pointer type (the cast sequence is B1* -> void* -> B2*):

struct B1 { int i; };
struct B2 { int j; };

struct D : B1, B2 { };

D x;
B1*   b1ptr   = &x;
void* voidptr = b1ptr;
B2*   b2ptr   = static_cast<B2*>(voidptr);

Attempting to use b2ptr here would result in undefined behavior. The only type to which you can safely cast voidptr is B1*, since that is the type from which the void* was obtained (well, or to a char*, since anything can be accessed via a char*).

物价感观 2024-09-18 19:05:36

编译器不会将 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文