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

Mehrdad wfunction at hotmail.com
Thu Aug 16 16:35:46 PDT 2012


On Thursday, 16 August 2012 at 23:18:08 UTC, Jesse Phillips wrote:
> Note that stronger guarentees does not translate to inferences 
> done by the compiler.

I remember being told (correct me if I'm wrong) that D's const 
lets the compiler perform better optimizations than C++, which 
i.e. means the compiler can infer more about the source code.


> The const page does have a comparison table at the end:
>
> http://dlang.org/const3.html

That just tells you how to use const, not why it's useful 
compared to C++.


> The main thing given is transitivity.

Sure, but what kind of an advantage does that provide compared to 
C++?
(As in, a code sample would be awesome -- it's so much easier to 
explain with an example to compare, rather than with words.)


> The compiler will guarantee you aren't changing data that is 
> const.

Right, but it's the same with C++, right? Where's the difference?



> On the note of casting away const, I don't believe that is the 
> operation which is undefined, however modifying const is 
> undefined as it could be pointing to immutable data.

Oh, then that's not what I'd understood. Seems just like C++ then.



> I believe there is an article which speaks to const, but the 
> inference benefits come from immutability and pure functions.

Ahh, right. You need immutability and purity for const to be any 
more advantageous than in C++. It seems like it's a point worth 
emphasizing in the const article (and perhaps when explaining 
const to newbies), since people might not understand why const is 
powerful unless they actually start using immutability, too.
(Also kind of prevents the situation where C++ users try to use 
const as logical const, without realizing that it's meant to work 
with immutability/purity instead.)


More information about the Digitalmars-d mailing list