[Issue 4331] New: Not called struct invariants

d-bugmail at puremagic.com d-bugmail at puremagic.com
Wed Jun 16 10:39:18 PDT 2010


http://d.puremagic.com/issues/show_bug.cgi?id=4331

           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
        AssignedTo: nobody at puremagic.com
        ReportedBy: bearophile_hugs at eml.cc


--- Comment #0 from bearophile_hugs at eml.cc 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: http://d.puremagic.com/issues/userprefs.cgi?tab=email
------- You are receiving this mail because: -------


More information about the Digitalmars-d-bugs mailing list