Bug 24034 – Changing this in constructor allows to modify immutable members of other instance

Status
RESOLVED
Resolution
FIXED
Severity
regression
Priority
P1
Component
dmd
Product
D
Version
D2
Platform
x86_64
OS
Linux
Creation time
2023-07-06T15:39:24Z
Last change time
2024-03-23T21:28:47Z
Keywords
safe
Assigned to
No Owner
Creator
Tim
See also
https://issues.dlang.org/show_bug.cgi?id=24024

Comments

Comment #0 by tim.dlang — 2023-07-06T15:39:24Z
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