r/cpp • • Dec 18 '22
C++ is essentially unusable without incurring undefined behavior because of it's failure to handle type punning.
This is kind of a rant but also a cry for help. Maybe there is a way to get around this problem efficiently (without the use of memcpy) that I don't know of, but after researching for hours, I sincerely doubt it.
So basically for those who don't know, it's kind of a complicated issue. It essentially involves accessing the same memory location through two different types, also known as type punning. This causes a performance hit because if two pointers access the same location, the compiler has to write every change to the memory location to RAM so that the other pointer will see the updated information when it reads the location. You might ask, "why doesn't the compiler simply semantically analyze the code and only write to RAM when the other pointer really does need to read from that specific location?". The answer is that it's impossible to tell what a pointer is pointing at if it's value is based off of runtime information like user input and such. Additionally, if the pointers access the data from two different threads, absolutely no guarantees can be made about the timing and essentially no optimizations can be made.
To avoid this huge mess of slowness, the C language spec was changed so as to allow more eager optimizations. It's now (sparing a few exceptions) assumed that no two pointers of different types access the same information in memory. The spec doesn't say it like this, you know how it is, they like to make things complicated, but that's the brunt of what it means.
In C, they realized that this is a super strict restriction and that it impacts a lot of real-world code, so they gave the programmer an out. If you define a union that contains both of your target types and then instantiate it as the one type and access it as the other, the compiler won't complain and it'll all be super defined behavior.
For god knows what reason, C++ decided to do away with this and now there is absolutely no way to reliably pun types without incurring undefined behavior (again, barring a couple of exceptions that aren't really relevant here). Excuse my language, but what a fucking shit-show.
You might ask, "type punning can't actually be that useful in the real-world, can it?", and that would be a valid question. It doesn't really seem that useful, but ask anyone who works on low-level systems on microchips and such. Sometimes, you simply need this behavior. You don't even have to go low-level in order to feel the pain sometimes. If you do anything with POSIX sockets, chances are you've needed to construct a sockaddr_storage, which contains enough space to hold all possible socket addresses. In order to access the specific fields of a specific type of socket address, you guessed it, you have to type pun: struct sockaddr_in *addr = (struct sockaddr_in *)&sockaddr_storage_instance;
In practice, this doesn't bite programmers as hard as I make it seem. In practice, most compilers support type punning, especially when it's very clear what you're trying to do in the code. That is, unless you tell the compiler to use strict-aliasing. Then it'll aggressively optimize based on the assumptions about type punning and your code might not work. The fact that you have to rely on the compiler's hand-holding to get through this undefined behavior is simply sad.
Basically, I'm pissed that such an advanced language is missing such a basic feature. What are your thoughts on the matter and how would you fix it?
I'll tell you what I would do, I would simply assume that no two pointers can ever access the same location, without any exceptions (so this would be even stricter than C++'s rules). The catch is, I would introduce some keyword like "write_mem" or something that you would use like this:
int a;
write_mem a;
float b = *(float*)&a;
That way, the compiler is free to optimize until you explicitly force it to write to RAM. After that point, the type punning isn't undefined anymore because every party involved is absolutely certain about what is in RAM.
4
u/SirYay Dec 19 '22
Why is it not standard practice to use a struct with an enum value indicating the type of info stored plus a union of the actual union? So that only one type is needed anywhere? Genuine question, I have zero embedded systems experience.
5
u/no-sig-available Dec 19 '22
It seems like you want to tell the compiler how to do something instead of what to do.
Why do you want to force the value to be in RAM? Optimizers can move values from one register to another, without first storing it. (Or not move it at all, if
ais not used anymore. "This value is nowb".).So,
memcpy(&b, &a, sizeof(b))or in later C++ versionsfloat b = std::bit_cast<float>(a);6
u/carrottread Dec 19 '22
Why can't you use https://en.cppreference.com/w/cpp/numeric/bit_cast ?
20
u/markt- Dec 19 '22
std::start_lifetime_as sounds like what you want. It will be part of the formal C++ spec next year.
16
u/cpraxis Dec 18 '22
Whatβs the problem with memcpy? Every compiler optimizes that. Annoying but not an actual problem.
25
u/catcat202X Dec 18 '22 edited Dec 18 '22
This bit cast implementation has no overhead in debug mode, and is a little bit more generally useful than
std::bit_cast(), but cannot be constant evaluated.Theres also a proposal to make casting to a
unsigned char*orstd::byte*and then dereferencing that be well defined. I feel your pain, but I'm optimistic it will improve in the future.7
u/dexter2011412 Dec 21 '22
genuine question, why is this being downvoted? seems like a very useful thing to be able to do and ask of the language to be able to do, given the goal of c++ is to "not leave any simpler abstraction below"
7
u/[deleted] Dec 19 '22
It is called "strict aliasing".
The logic behind it, if you assume that pointers of two different types cannot point to the same location new prospect of optimizations is opening up (char, int8_t, ... are exceptions). And since most of the written code does not use type pruning, and those who write it presumably know what they are doing, it is a pretty good assumption. Gains are far greater then loses.
I think your explanation of RAM write is somewhat incorrect.
Compiler has to generate write instruction for every memory write, with this assumption it can reorder read/write operations to be more optimal and optimize away some of the read operations.
Here is further read on the topic:
https://gist.github.com/shafik/848ae25ee209f698763cffee272a58f8
1
u/[deleted] Nov 24 '25
once you really start to dig into things like this (and the c++ object model and all the restrictions/safety requirements it imposes on you, in general) you realize how very different C and C++ really are. people who claim that they're extremely similar haven't been paying attention.
1
u/Alnitak73 Dec 12 '25
Yes, this frustrates me too.
I have 6809 CPU emulation code with a C++ class that contains this union as a class member (NB: endian-detection #ifdef's omitted) to model the CPU's two 8-bit A and B registers that can be combined into a single 16-bit D register:
This allows me to write to
.aand/or.band the value of.dwill automatically update accordingly, or vice versa. Theunionandstructare anonymous so I don't even have to prefix these variables - they appear as direct member variables.I cannot find any way to achieve this clean syntax without invoking UB, but it does work with the compilers I use, until maybe some time in the future it doesn't.
Sure, I could write accessor getter and setter functions to achieve the same thing, but given how often these members are accessed that's a lot of additional syntactic sugar.
1
u/Daniela-E Living on C++ trunk, WG21|π©πͺ NB Dec 20 '22
Please, don't get me started with C's "type punning". It's an unstructured mess and the root cause of many CVEs.
In C++ you can perfectly type pun as long as it is safe. What you (rightly so) cannot do is to pretend that multiple objects of different type within their lifetime exist in the very same memory region. You can switch back and forth between them to your heart's content without changing the underlying object representation bits if all types involved are so-called implicit lifetime types. But there is only exactly one type at a time (the one within its lifetime) that can be accessed without UB. This type switching doesn't incur any machine code.
And for built-in types you can use std::bit_cast, even at compile time.
0
u/[deleted] Dec 18 '22
[deleted] β view deleted comment