3 ms·
const_cast risk is not why the compiler emits a reload. Indeed we don't even need to pass x to constFunc to get the reload: see line 7 in https://godbolt.org/z/
by ridiculous_fish 7y ago
const_cast risk is not why the compiler emits a reload. Indeed we don't even need to pass x to constFunc to get the reload: see line 7 in https://godbolt.org/z/TjmWxL https://godbolt.org/z/TjmWxL
Consider that `x` may point to a global variable which `something` may modify. That is why the reload is necessary.
edit: I just realized that the reload would be necessary even without an intervening function call. https://godbolt.org/z/QhVzlV https://godbolt.org/z/QhVzlV
Consider that `x` may point to errno; then printf would modify it!
- hermitdev 7y agoThe reload shouldnt be necessary unless there is an appropriate memory barrier, though. Seems like the compiler is being pessimistic in the examples.
- einpoklum 7y agoYou're mistaken. What you're thinking of is a pointer to a _volatile_ ; for a regular pointer, you only need one load - even if it's not a pointer-to-const. See: https://godbolt.org/z/XWW9Nq https://godbolt.org/z/XWW9Nq
- amalcon 7y agoI think you're talking past each other. Grandparent is examining the case where there is a function call (the printf), but you do not pass anything relevant into it. You're looking at the case where there is no function call, so peephole optimization can observe that the memory at that location can't change. "volatile" basically tells the compiler "Hey, wait, this might be modified by DMA, another thread, or another process. Assume nothing."