Summary: Not called struct invariants
           Product: D
           Version: D2
          Platform: All
        OS/Version: All
            Status: NEW
          Keywords: accepts-invalid
          Severity: enhancement
          Priority: P2
         Component: DMD

--- Comment #0 from 2010-06-16 10:39:17 PDT ---
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.

Configure issuemail:
------- You are receiving this mail because: -------

Reply via email to