[Issue 23780] New: Manual __ctor call can mutate immutable object in @safe code
d-bugmail at puremagic.com
d-bugmail at puremagic.com
Wed Mar 15 04:35:20 UTC 2023
https://issues.dlang.org/show_bug.cgi?id=23780
Issue ID: 23780
Summary: Manual __ctor call can mutate immutable object in
@safe code
Product: D
Version: D2
Hardware: All
OS: All
Status: NEW
Severity: normal
Priority: P1
Component: dmd
Assignee: nobody at puremagic.com
Reporter: snarwin+bugzilla at gmail.com
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.
--
More information about the Digitalmars-d-bugs
mailing list