Bug 21665 – Void initialization should not be allowed for instances of struct with invariant
Status
RESOLVED
Resolution
FIXED
Severity
normal
Priority
P1
Component
dmd
Product
D
Version
D2
Platform
All
OS
All
Creation time
2021-02-27T05:58:13Z
Last change time
2021-04-06T09:02:12Z
Keywords
pull, safe
Assigned to
No Owner
Creator
Walter Bright
Comments
Comment #0 by bugzilla — 2021-02-27T05:58:13Z
struct ShortString {
private ubyte length;
private char[15] data;
@safe
this(const(char)[] src) {
length = cast(ubyte) src.length;
data[0 .. src.length] = src[];
}
@trusted
const(char)[] opIndex() const {
// should be ok to skip the bounds check here
return data.ptr[0 .. length];
}
invariant { assert(length <= data.length); }
}
If this is void initialized,
@safe test() {
ShortString s = void;
char c = s[16];
}
Then the value in .length is unpredictable, so the invariant may not be satisfied. So, in @safe code, void initializations of struct objects when the struct has an invariant should not be allowed.
The same holds true for unions, such as:
union U {
int n;
ShortString s;
}
Examples by Dennis Korpel and Paul Backus.
Comment #1 by dlang-bot — 2021-03-31T08:31:25Z
@WalterBright created dlang/dmd pull request #12326 "fix Issue 21665 - Void initialization should not be allowed for insta…" fixing this issue:
- fix Issue 21665 - Void initialization should not be allowed for instances of struct with invariant
https://github.com/dlang/dmd/pull/12326
Comment #2 by dlang-bot — 2021-04-06T09:02:12Z
dlang/dmd pull request #12326 "fix Issue 21665 - Void initialization should not be allowed for insta…" was merged into master:
- 72b737a626e3088b829cdde29ed51c6c00a308e8 by Walter Bright:
fix Issue 21665 - Void initialization should not be allowed for instances of struct with invariant
https://github.com/dlang/dmd/pull/12326