First off, I come from a "managed" land, so be gently. I'm trying to create a messaging system and before I put too much effort into it, I want to make sure my understanding of casting is correct.
Say I have a pod type called header and place that header into another pod type message, can I safely static_cast the message to header and reinterpret_cast the header pointer to a message pointer?
If I understand correctly, casting to the first member of a pod is safe, and reinterpret cast should be safe for returning to my original pointer?
example:
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;
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…