Bug 4331 – Struct invariants not called

Status
RESOLVED
Resolution
DUPLICATE
Severity
enhancement
Priority
P2
Component
dmd
Product
D
Version
D2
Platform
All
OS
All
Creation time
2010-06-16T10:39:00Z
Last change time
2010-06-17T13:08:26Z
Keywords
wrong-code
Assigned to
nobody
Creator
bearophile_hugs
Blocks
2573

Comments

Comment #0 by bearophile_hugs — 2010-06-16T10:39:17Z
Struct invariants are useful to restrict the number of possible states of a struct instance. But there are situations where they are not called&run. This D2 program compiles and runs with no errors with 2.047: struct Foo { int x; invariant() { assert(x > 0); } } void main() { Foo f = Foo(-10); } To avoid this I can see two possible solutions: 1) When a struct is initialized through the built-in constructor using user-specified values, as in this case, the compiler can call the invariant() at the end of the initialization. So this code can assert at run-time (or even at compile-time if the compiler is smart) and avoid possible bugs. 2) If the precedent option is not possible, then the compiler has no way to enforce the invariant of this struct Foo (calling f.__invariant() from user code is not a solution). There is no point to keep an invariant if D never enforces it, it's bad to give a false sense of security to the programmer. So the compiler can refuse an invariant at compile-time where it can't be enforced, with an error message.
Comment #1 by smjg — 2010-06-16T11:27:33Z
The StructBodyDeclaration syntax (both D1 and D2) includes Invariant. Therefore the code is legal, and the bug is that the compiler ignores it.
Comment #2 by bearophile_hugs — 2010-06-17T13:08:26Z
*** This issue has been marked as a duplicate of issue 519 ***