Re:Hello. I'm a compiler
by AshleysBrain on Tuesday February 19, 2013 @09:48AM
(#5244517)
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.
[ Parent
| on HN ]
Re:Hello. I'm a compiler
by koenigdavidmj on Tuesday February 19, 2013 @01:47PM
(#5246201)
I'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 :(
If 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.
Re:Hello. I'm a compiler
by AshleysBrain on Tuesday February 19, 2013 @12:33PM
(#5245648)
Do 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.
That 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.