The following program does not compile:
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
The reason is that the context pointer stored in a is const, and thus implies that the context it points to is also const. This cannot be copied to the non-const context pointer in b.
This context pointer is not, however, actually treated as const. The following code compiles and passes:
unittest {
int i = 0;
struct S {
int n;
void fun() const {
i++;
}
}
const S s;
assert(i == 0);
s.fun();
assert(i == 1);
}
Full discussion thread at https://forum.dlang.org/thread/[email protected]
I would argue that the correct solution is to allow the assignment.
Comment #1 by timosesu — 2018-07-19T08:43:00Z
Related: https://forum.dlang.org/post/[email protected]
// dmd v2.081.1
unittest {
struct S {
uint value;
~this() pure {
}
}
S makeS() pure
{
S s = S();
return s;
}
// Error: cannot implicitly convert expression makeS() of type S to immutable(S)
immutable S s = makeS();
}
Without the destructor compiles fine.
Perhaps a better error message could be found.
Further related issue: https://issues.dlang.org/show_bug.cgi?id=18567
Comment #2 by robert.schadek — 2024-12-13T18:57:38Z