3 ms·
Concerning #2: Does 'const' mean that the function is not allowed to change the contents of the string, or does it mean that the contents of the string will ne
by afhof 16y ago
Concerning #2:
Does 'const' mean that the function is not allowed to change the contents of the string, or does it mean that the contents of the string will never change? Suppose the 'sum' function was running in one thread, while in another the string that was passed in as 's' is being continuously written to. While this may not make much sense to do, and the output would not have a reliable value, this optimization would be the wrong thing to do.
- okmjuhb 16y agoconst only means that the function is not allowed to change memory through that reference. It says nothing about aliases to the same memory. But the "what if another thread changes the string" issue is a red herring. The question to keep in mind when optimizing in a multi-threaded context is "does the output of the compiler generated code correspond to at least one possible interleaving of threads". Since this thread doesn't do any synchronization, it's possible that all the function executes without being interrupted by another thread, so this is a sound optimization.
- murrayh 16y agoYou can prevent caching optimisations by declaring a variable 'volatile' (http://en.wikipedia.org/wiki/Volatile_variable http://en.wikipedia.org/wiki/Volatile_variable).