I found a place where some weird casting was happening, and I wanted to confirm if someone knew it was legal.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
|
// Example program
#include <iostream>
struct Small {
int data;
};
struct Big {
Small small;
int more_data;
};
int main()
{
Big big { {42}, 100 };
Small* small = (Small*)(&big);
small->data = 43;
std::cout << small << '\n'
<< &big.small << '\n'
<< small->data << '\n'
<< big.small.data << '\n';
}
| |
0x7d0b336ecec0
0x7d0b336ecec0
43
43 |
Is the above example undefined behavior (Specifically, casting the Big* to a Small*)?
My guess is that this is actually legal, because of "reinterpret_cast" shenanigans, but I'm not sure.
Second code is the dual of this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
|
// Example program
#include <iostream>
struct Small {
int data;
};
struct Big {
Small small;
int more_data;
};
int main()
{
Small small { 42 };
Big* big = (Big*)(&small);
big->small.data = 43;
std::cout << &small << '\n'
<< &big->small << '\n'
<< small.data << '\n'
<< big->small.data << '\n';
}
| |
0x7bc5f88d45c0
0x7bc5f88d45c0
43
43 |
Is this legal, so long as big->more_data is not accessed?
Again, my guess is that it is legal, and this is why the address of the first member of a struct is the same as the address of the struct.
And does anyone know what this construct or method is called, regardless of its legality (if it has a "name")? Would you just call it "object slicing", despite not using inheritance?
PS: Obviously this is horrible code that is hard to read. I'm trying to make existing code better.