3 ms·
> When the & operator is used on 'a' it should mark it as unsafe to place the 'a' on a CPU register Not necessarily, as the compiler might be smart enough to a
by MaxBarraclough 6y ago
> When the & operator is used on 'a' it should mark it as unsafe to place the 'a' on a CPU register
Not necessarily, as the compiler might be smart enough to adjust the other operations and enregister the a variable anyway. There's no ceiling on how smart the optimiser can be. An extreme case:
int a = 42;
&a;
// do things with 'a'
This uses the & operator but doesn't even save the result of the expression, so the compiler will presumably chop that whole second statement as dead code, and may still be able to enregister a.
> optimizations should never affect how the program behaves (except making it run faster, of course)
Most of the time a C++ compiler's optimiser must preserve observable behaviour, provided undefined behaviour is not invoked, but not always. C++ permits elision of certain copy/move operations even if this changes observable behaviour. [0]
Also, if the program is multithreaded and has race conditions, an optimiser isn't required to ensure that the relative speeds of different threads remains unchanged, which may lead to a change in observed behaviour. Of course, in such a case, except making it run faster contradicts never affect how the program behaves, so you've sort of covered that anyway.
[0] https://stackoverflow.com/a/12953129/ https://stackoverflow.com/a/12953129/
- badsectoracula 6y agoSure, if a compiler can do that with 100% certainty, it can use a register for it. However that '100%' comes after it treats &a as a pointer until the very moment it is '100%' sure. Also FWIW i was referring to C, not C++. C pointer optimizations can easily chop off your leg, C++ basically adds poison just in case you survive the blood loss.