Why does this not compile?

Shachar Shemesh shachar at weka.io
Tue Mar 6 10:03:54 UTC 2018


void main() {
     struct S {
         uint value;

         ~this() {
         }
     }

     const S a = S(12);
     S b = a;
}

test.d(10): Error: cannot implicitly convert expression a of type 
const(S) to S

Doing *any* of the following makes the code compile:
* Making the struct "static"
* Making the struct global (essentially same as above)
* Removing the struct's destructor

I can kinda see why it won't compile without making it static. There is 
a hidden pointer to the frame that is const, implying the frame is also 
const. This constness would be overridden if the assignment is allowed 
to go through. I don't think this is a very good reason (see below), but 
I understand it.

What I do not understand is why removing the destructor solves the error.




While I get while the compiler treats the frame pointer as const, I 
should point out that if I add a static variable to the struct, that one 
remains mutable even when the instance itself is const. There is no 
inherent difference between a variable stored as static and a variable 
stored in the context frame.

And before you answer with "in D pointer constness is transitive", allow 
me to point something out: It is not possible to ever change the frame 
pointer of a struct. That pointer is, effectively, always const.

Shachar


More information about the Digitalmars-d mailing list