On Sun, 25 Jan 2015 22:06:26 +0000, Bayan Rafeh wrote:
> This is another problematic example program:
> import std.stdio;
>
> void main(){
> auto a = new A("/tmp/invalid");
> }
>
> class A {
> File f;
> string path;
>
> this(string path) {
> this.path = path;
> // f = File(path, "r");
> }
>
> invariant() {
> File test = File(path, "r");
> }
> }
>
> is invariant() called during the destruction phase?the thing is that your invariant is not a correct invariant at all. invariants are meant to check *internal* object consistency, not external conditions. compiler is free to call invariant block at any time after object is properly initialised (i.e. after ctor is complete) and is not executing member method. so it's perfectly legal to call invariant before dtor, as you should not check anything that is not belonging to the object itself in in. in other words: you can't check any contents of any reference-typed variables in your invariant block. `string` is reference-typed (it's a dynamic array managed by GC in your case), so you can't check it contents in invariant. you CAN, however, use `f` methods in your invariant, as `f` is a struct which lives *inside* your object, and not a reference var. but note that it's a bad practice anyway, as some struct can use some GC- managed objects which can't be safely used in invariant block.
signature.asc
Description: PGP signature
