Pull request https://github.com/dlang/dmd/pull/15389 for issue 24024 allows to modify `this` for classes inside functions. In constructors this allows to modify immutable members of another instance of the same class. The constructor will now also return the wrong pointer.
import std.stdio;
class C
{
immutable int i;
this(int i, C other)
{
if (other !is null)
this = other;
this.i = i;
}
}
void main()
{
C c1 = new C(1, null);
writeln(c1.i); // prints 1
C c2 = new C(2, c1);
writeln(c1.i); // prints 2
writeln(c2.i); // prints 2
writeln(c1 is c2); // prints true
}
Comment #1 by razvan.nitu1305 — 2023-07-10T11:47:59Z
Yeah, this is bad. I guess `this` should not be modifiable for classes when used in constructors. For normal functions it could be allowed.
Comment #2 by nick — 2024-03-23T21:28:47Z
The pull for issue 24024 was reverted and it was marked WONTFIX.
Assignment to `this` now gives:
thislval2.d(8): Error: cannot modify expression `this` because it is not an lvalue