[Issue 21665] New: Void initialization should not be allowed for instances of struct with invariant
d-bugmail at puremagic.com
d-bugmail at puremagic.com
Sat Feb 27 05:58:13 UTC 2021
https://issues.dlang.org/show_bug.cgi?id=21665
Issue ID: 21665
Summary: Void initialization should not be allowed for
instances of struct with invariant
Product: D
Version: D2
Hardware: All
OS: All
Status: NEW
Severity: normal
Priority: P1
Component: dmd
Assignee: nobody at puremagic.com
Reporter: bugzilla at digitalmars.com
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.
--
More information about the Digitalmars-d-bugs
mailing list