Bug 23780 – Manual __ctor call can mutate immutable object in @safe code

Status
NEW
Severity
normal
Priority
P1
Component
dmd
Product
D
Version
D2
Platform
All
OS
All
Creation time
2023-03-15T04:35:20Z
Last change time
2024-12-13T19:27:49Z
Keywords
accepts-invalid, safe
Assigned to
No Owner
Creator
Paul Backus
Moved to GitHub: dmd#20248 →

Comments

Comment #0 by snarwin+bugzilla — 2023-03-15T04:35:20Z
As of DMD 2.102.2, the following program compiles successfully and causes an assertion failure when run: --- struct S { int n; @safe this(int n) immutable { this.n = n; } } @safe void main() { immutable S s = 123; int before = s.n; s.__ctor(456); assert(s.n == before); // fails } --- The cause of the assertion failure is the mutation of the immutable object `s` by the call to `S.__ctor`. Since constructors are allowed to mutate immutable objects for the purpose of initialization, @safe code must not be allowed to call the constructor of an existing object, even if that constructor is @safe.
Comment #1 by razvan.nitu1305 — 2023-03-15T11:22:10Z
Yes, manually calling __ctor in @safe code should be disabled.
Comment #2 by snarwin+bugzilla — 2023-10-29T17:48:06Z
Unfortunately this will probably be tricky to fix, because a lot of valid code gets lowered to `obj.__ctor` internally by the DMD frontend.
Comment #3 by robert.schadek — 2024-12-13T19:27:49Z
THIS ISSUE HAS BEEN MOVED TO GITHUB https://github.com/dlang/dmd/issues/20248 DO NOT COMMENT HERE ANYMORE, NOBODY WILL SEE IT, THIS ISSUE HAS BEEN MOVED TO GITHUB