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;
}
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With