Re:Add a const here, delete a const there
by brucedawson on Monday January 09, 2017 @12:26PM
(#13357946)
Author here. I'm a big believer in adding const everywhere - local variables, globals, member functions, etc.
Marking globals as const can move them to the read-only segment which has some modest performance improvements, but in most other cases const doesn't affect code-gen at all. Using const prevents programmers from doing certain things, and the compiler enforces that. That suggests that the compiler already knows whether or not programmers are doing those things - it doesn't need a 'const' hint to tell it. And in those cases where it can't tell, the 'const' hint is usually not sufficient for it to depend on.
In short, with the exception of moving globals to the read-only segment I am not aware of any performance improvements from using const.
Re:Add a const here, delete a const there
by wfunction on Monday January 09, 2017 @03:31PM
(#13359514)
> What's the drawback for a const member?
Check out this subthread: https://news.ycombinator.com/item?id=13356101
IMO `const` should be used liberally: members, locals and other declarations.
When you're on a team and you have a data structure that has const members, it should give that newer/unfamiliar team member pause when they get the compilation error because they added a method that modifies the `const` member. Now they have an opportunity to take a step back and ask "Oh, why was it designed this way? What other assumptions in the code are invalidated if I need to remove the `const`?"
`const` for locals is good for those notorious ten-line functions that over time multiply into a 150-line function. Yes, we should refactor that mega function into something easier to digest. But right now I am trying to figure out this bug: I can see that ^^ up there 'foo' was initialized as a particular value, and down here it looks like it must have changed. Instead of looking through all of the hundred lines of code to see who might've updated 'foo', I know right away that a likely explanation is stack corruption.
This is BTW why I love that rust has opt-in mutability. It feels almost a little silly sprinking `const` thither and yon when it's only a few select places that it's actually un-needed.