静态和重新解释铸造-定义的行为?
首先,我来自一个“管理”的土地,所以要温柔。我正在尝试创建一个消息传递系统,在我投入太多精力之前,我想确保我对转换的理解是正确的。
假设我有一个名为 header 的 pod 类型,并将该 header 放入另一个 pod 类型的消息中,我可以安全地将消息 static_cast 到 header 并 reinterpret_cast 将头指针指向消息指针吗?
如果我理解正确,转换到 pod 的第一个成员是安全的,重新解释转换应该可以安全地返回到我的原始指针?
例子:
struct Header
{
int m_size;
int m_type;
};
struct Message
{
// first member to static cast to..
Header m_header;
};
//
int main()
{
Message msg;
// cast to the first member, the header.
auto* hdr = static_cast<Header*>(&msg.m_header);
// because I know the message by type, safely cast it back to the original message type.
Message* tmp = reinterpret_cast<Message*>(hdr);
return 0;
}
回答
我可以安全地将消息 static_cast 到标题吗
不。这种静态演员的形式不正确。类似的重新解释演员会很好地定义......只要你陈述的先决条件是真的。如果你错误地假设它们,那么程序的行为是未定义的。
正如评论中指出的那样,您的代码示例 static 将标头指针转换为标头指针,该标头指针当然定义良好,但不是您所询问的。
并 reinterpret_cast 头指针指向消息指针?
是的。