Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
405 views
in Technique[技术] by (71.8m points)

c++ - static and reinterpret casting - defined behavior?

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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

can I safely static_cast the message to header

No. Such static cast is ill formed. Similar reinterpret cast would be well defined though... As long as your stated preconditions are true. If you assume them wrongly, then behaviour of the program is undefined.

As pointed out in a comment, your code example static casts header pointer to a header pointer which is of course well defined, but not what you asked about.

and reinterpret_cast the header pointer to a message pointer?

Yes.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...