Compilers (at least clang and gcc) are smart enough to see through those memcpy's. For example:
void write32(int *ptr, int val) {
memcpy(ptr, &val, 4);
}
…the load is removed entirely, and the store is kept but becomes a native store: write32:
mov DWORD PTR [rdi], esi
ret
Godbolt link: https://godbolt.org/g/HYv24FThat's worse though because compiler optimization are wholly unreliable. Maybe today, maybe not tomorrow. And you have utterly no control over that.
This just highlights why strict aliasing rules exists. Because the exact same alignment problems is what you get when you type pun. Looking at the raw data as a char* or memcpy'ing it just makes it more visible that what you are doing is wrong.
The only valid reason to do type punning is to serialize data and then deserialize it back to exactly the same type. And since type puning with char* is defined as ok so there is no problem. I am having a really hard time seeing other valid reasons to do type punning and have never ever had to use it myself.
Seriously, why are people upset over strict aliasing? What is the valid use case for type punning that people are missing?
2. If you are trying to retrofit polymorphism in C maybe you are using the wrong tool for the job.
3. If you really want polymorphism you can create baseclass-struct with a void* this pointer and a bunch of function pointers as instance-functions. To "override" the struct you just instantiate it with different function pointers. If you want to inherit an existing struct you add a void* super-member into your this-data and instantiate it explicitly. For any function you don't want to override you use just call the existing function function and pass in you super-data as this.
This is also safe as each subclass implementation only casts the void* this into itself which is a known struct of the same type as was last written to. You do have to split the data and keep super-class data in another struct one pointer-hop away but that shouldn't be a big issue.
Writing to union member and reading back as another member should be okay. But it does incur copy.
https://stackoverflow.com/a/11996970
Since Linux is C, not C++, it should be fine; the author of the patch is just mistaken.
(Note that in practice, this will work in C++ too, since most compilers support both C and C++ and don't change their optimization behavior based on which mode the code was compiled in; but of course there's no guarantee this won't change in the future.)
But furthermore, this will really only work for scalars. Plus you have to go and declare a whole new type to cast things safely. It's extremely awkward.
struct Person {
char *name;
unsigned char age;
}
struct Teacher {
struct Person person;
char *subject;
}
This kind of code is pretty common in C, and memcpy doesn't (can't) handle it.(also hey Ted I'm a huge fan of your work, thanks in particular for threading, holy shit)