immutability and constness

Minas Mina minas_mina1990 at hotmail.co.uk
Wed Jul 11 17:14:30 PDT 2012


I'm fairly new to D, but I have been using C++ for a while now 
(about 5 years, selftaught).

 From what I have learned, const in C++ is inconsistent.

For example:

int main()
{
    const int x = 0; // could be placed in ROM because it's known 
at compile time
}

void f(int x)
{
   const int y = x * x; // logical const
   // blah blah blah
}

const can be also cast away (const_cast if I remember correctly - 
I wasn't doing it often :) ) and mess everything.

 From what I understand, immutable in D is truly immutable. But I 
have seen some code here on the forum that casts aways 
immutability... (Is that even defined behaviour? What if that 
thing was in ROM?)

D has const as well... This is were it becomes a bit tricky for 
me. To be honest, I haven't got the book about D - it should(does 
it?) have information about that.

Can someone explain what are D's goal about immutable, const - 
and why it is bitwise const and not logical? How does it benefit 
programs? I have read something about that in the "general 
discussions" forum but posted the question here because it's for 
me (and others) to learn about that.

Thanks.


More information about the Digitalmars-d-learn mailing list