It's the optimization that C++ is unable to perform, not the immutability.
If you declare using an invalidated iterator as UB, the compiler can optimize as if the container was effectively immutable during the loop.
Re:C++ Is an Absolute Blast
by CyberDildonics on Tuesday December 24, 2024 @10:22AM
(#42502447)
Are you talking about optimizing out bounds checking that isn't happening in the first place?
Re:C++ Is an Absolute Blast
by jodrellblank on Tuesday December 24, 2024 @11:38AM
(#42502982)
> "They asked for evidence of bounds checks being expensive"
They said "bounds-checking penalties are small" not that it was free. You've described a situation where bounds checking happens and declared that it "should be" expensive because it happens. You haven't given evidence that it's expensive.
Re:C++ Is an Absolute Blast
by CyberDildonics on Thursday December 26, 2024 @06:15PM
(#42518619)
I didn't give direct evidence, that's true.
You can profile it yourself, but it is the difference between direct access to cached memory (from prefetching) and two comparisons plus two branches then the memory access.
To someone who doesn't care about performance having something trivial become multiple times the cost might be acceptable (people use scripting languages for a reason), but if your time is spent looping through large amounts of data, that extra cost is a problem.
Note that this is not something C++ is able to do
Or you could just not mutate the container.