为什么不允许将void *的static_cast转换为其他类型?

Dav*_*hun 6 c++ pointers casting void-pointers static-cast

我只是在阅读此线程: 简单的c ++指针转换

这使我开始思考为什么不允许在不同的指针类型之间进行static_cast(除非在这种情况下除外),除非您将static_cast转换为void *作为中间步骤。在我看来,这两者都不应该允许。这是一个例子:

char*          cs;
unsigned char* ucs;

cs = reinterpret_cast<char*>(ucs);                  // 1) allowed, of course
cs = static_cast<char*>(ucs);                       // 2) not allowed: incompatible pointer types
cs = static_cast<char*>( static_cast<void*>(ucs) ); // 3) now it's allowed!
Run Code Online (Sandbox Code Playgroud)

在我看来,如果可能#3,那么也应该允许#2。或者相反,如果由于指针不兼容(需要reinterpret_cast)而不允许#2,则也许可能由于指针不兼容而不允许 void *到任何对象的static_casting 。(当然,从任何其他指针投射 void *总是可以的。)

那么,为什么其中一种可能性不成立-#2和#3要么都允许,要么都不允许?为什么反而如我的示例所示起作用?

Dav*_*eas 4

cs = static_cast<char*>( static_cast<void*>(ucs) ); // 3) now it's allowed!
Run Code Online (Sandbox Code Playgroud)

它将编译。是不是就代表允许了呢?不是。该标准仅在通过从 转换获得 的情况下才允许从 转换为void*,但T*您的情况并非如此。void*T*

  • 这是未定义的行为,理论上任何事情都可能发生。实际上,在您的特定情况下,它很可能有两个原因起作用。首先,这些类型仅在符号性上有所不同。第二个是“char*”很特殊,在标准中有特殊处理。无论如何,“static_cast”序列确实是不允许的,并且应该使用“reinterpret_cast”来完成转换。 (2认同)