2 ms·
Here is the gist of the explanation from the article: And there aren’t any rules against casting away const to modify an object that isn’t itself const. This me
by Too 10y ago
Here is the gist of the explanation from the article: And there aren’t any rules against casting away const to modify an object that isn’t itself const. This means the above (mis)behavior of foo isn’t undefined behavior for this call. Notice how the undefined-ness of foo depends on how it was called.
Wtf? This seems like a huge potential optimization gain missed. Surely by know it can't just be enabled because a lot of code would be written with the assumption above, I'm just curious for the rationale of this model. I don't understand the reasoning at all, why would you ever want to cast from a const to non const and have the behaviour depend on the type I pass to the function? Let's assume the signature of foo was faulty definied as const but still modifies x inside (faulty definined signatures for API compatibility seems to be the whole reason for allowing you to cast away const) and I pass int x, the the behaviour is definied but if I pass a const int x the behaviour is undefined?!? Clearly this is the fault of the person writing the foo function but how does that help me writing the bar function, I am not expected to know the whole call stack of foo, that's what the signature is for, I must be able to trust it's const correctness and that should not depend on what I pass into it.
If the optimization was always disabled I could understand the reasoning but now you get some kind of half assed middle ground where you as a caller must guarantee the actions of a callee.
- makapuf 10y agoIs there any portable way to tell the compiler it can do this kind of optimization in C ? Wouldn't that be useful ?