Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

static and reinterpret casting - defined behavior?

Tags:

c++

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;
}
like image 787
user3426850 Avatar asked Jan 07 '21 04:01

user3426850


People also ask

What is reinterpret cast?

The reinterpret_cast allows the pointer to be treated as an integral type. The result is then bit-shifted and XORed with itself to produce a unique index (unique to a high degree of probability). The index is then truncated by a standard C-style cast to the return type of the function.

What is the difference between static_cast and Dynamic_cast?

static_cast − This is used for the normal/ordinary type conversion. This is also the cast responsible for implicit type coersion and can also be called explicitly. You should use it in cases like converting float to int, char to int, etc. dynamic_cast −This cast is used for handling polymorphism.

What is the point of reinterpret_cast?

reinterpret_cast is a type of casting operator used in C++. It is used to convert a pointer of some data type into a pointer of another data type, even if the data types before and after conversion are different. It does not check if the pointer type and data pointed by the pointer is same or not.


1 Answers

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.

like image 172
eerorika Avatar answered Nov 10 '22 09:11

eerorika