Immutable objects and constructor ?

Mike Parker via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri May 20 19:35:33 PDT 2016


On Friday, 20 May 2016 at 16:09:54 UTC, chmike wrote:

>
> But I now met another error in my main(). I can't assign the 
> immutable object to a mutable reference.
>
> Info x1 = MyInfos.one;
>
> Is it possible to define a mutable reference to an immutable 
> instance ? 
>
> This is confusing and frustrating. In C++ we can write
> MyInfos {
>    . . .
>    // one is a constant pointer to a constant object of type Obj
>    Obj const * const one;
>    . . .
> }
>

I strongly advise you put C++ out of your head when programming D 
and try to come at it as if you have never seen C++. Otherwise, 
you will just keep getting frustrated. D is a different language 
and, while some C++ idioms may work just fine, others do not and 
cannot.

Consider this:

immutable(int*) ifoo;

Because the * is inside the parens in the declaration of ifoo, we 
are saying that we never want the pointer to be reassigned. The 
compiler is free to behave as if that is true and that ifoo will 
always point to the same address. It might make certain 
optimizations based on that guarantee that might not otherwise be 
possible. The same is true if you replace immutable with const in 
this particular declaration. If you somehow manage to circumvent 
that guarantee, then you are breaking the compiler's expectations 
and entering the realm of undefined behavior. You can think of an 
immutable class reference as being an immutable pointer like ifoo.

C++ has no such guarantees. The compiler is not free to make the 
same assumptions D can make. If D allowed you to do what C++ 
does, then D compilers would be in the same boat. This is one of 
the reasons why you can't expect D code to behave like C++ code 
in every case, no matter how similar things look on the surface.




More information about the Digitalmars-d-learn mailing list