4 ms·
Const doesn't actually help compilers (at least in C/C++ based languages). Since it can be const_cast away and still work in a standards compliant way, any opti
by AshleysBrain 14y ago
Const doesn't actually help compilers (at least in C/C++ based languages). Since it can be const_cast away and still work in a standards compliant way, any optimisation assuming const values never change is a bug. Instead the compiler will use other techniques, e.g. finding variables that are only written to on initialisation, and those don't even need to be marked const.
- koenigdavidmj 14y agoI've seen gcc turn a const bool& into a direct pass of a bool by value. Of course, I noticed this because it was the implementation of a web service binding, and the wrapper was going to pass me a bool& (as a pointer) whether I liked it or not. Instant segfault...but not always :(
- _kst_ 14y agoIf an object is defined as const, casting away its constness and modifying the object causes the program's behavior to be undefined. Compilers are free to take advantage of that.
- AshleysBrain 14y agoDo you have a spec reference for that? I was under the impression you could safely const_cast and modify pretty much anything. Perhaps it was just primitives like ints, or const member functions.
- mikeash 14y agoThat is true, but it's extremely rare to be able to take advantage of that. When people think of const as a potential optimization aid, it's almost always in the context of const pointers, which actually do nothing at all for optimization.