What guarantees does D 'const' provide, compared to C++?

Jesse Phillips Jessekphillips+D at gmail.com
Fri Aug 17 14:25:30 PDT 2012


On Friday, 17 August 2012 at 01:51:38 UTC, Mehrdad wrote:
> If you did, then the code would be invalid, and the compiler 
> could simply format your C: drive instead of modifying the 
> object.

This is probably the worst discussion point when people talk of 
why undefined behavior is bad.

It is true in that you won't know what happens when in an 
undefined state, but it is false in that, if it formats your C 
drive then ~you'd have to be running Windows~, that would be 
defined behavior and the spec would have said "Implementation 
Defined"

Which actually brings another point "Implementation Defined" is 
then just as bad as Undefined because the compiler can do 
whatever it wants! (And yes I know it is bad too).

The reason it is left undefined is because either it would have 
to be prevented by the compiler, or some other change to the 
specification would have to be made in order to define the 
behavior (which would be an addition not desired).

In the case of D, we define casting, thus you can cast away 
const. But after that the compiler holds no record it was const, 
nor does it make any attempt to move the data into read only 
memory, and thus, if the variable is located in writable memory 
it can be changed.

The question you are asking I do not have an answer for. I will 
try repeating it here in case it clarifies for them.

Without the presence of immutable/pure, what can the compiler do 
with code that is marked as const that improves performance which 
is not done in C++. (Actually I'd like to know those which C++ 
preforms too).


More information about the Digitalmars-d mailing list