Enforcing checks for return code

Marc Schütz via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Feb 18 02:46:03 PST 2016


On Thursday, 18 February 2016 at 07:21:05 UTC, Chris Katko wrote:
> Hello. I'm almost brand-new to the D language and still 
> absorbing things.
>
> I'm wondering if it's possible to fire off a compile-time (or 
> worst case, a run-time) warning or error if a function is 
> called, but the return value is not checked.
>
> I'm not trying to enforce whether someone actually deciphers 
> the value's meaning correctly. I just want to enforce that 
> somewhere, a variable or expression is receiving the return 
> value of a particular function.
>
> Any ideas?
>

As Jonathan said, there's no such built-in feature, and exception 
are preferred over return codes. However, you can implement such 
a check at run time:

struct ForceCheck(T) {
     private T payload;
     private bool checked = false;
     @disable this();
     @disable this(this);
     this()(auto ref T payload) { this.payload = payload; }
     ref T get() {
         this.checked = true;
         return payload;
     }
     alias get this;
     void ignore() {
         this.checked = true;
     }
     ~this() {
         assert(this.checked, "you forgot to check the return 
value");
     }
}

auto forceCheck(T)(auto ref T value) {
     return ForceCheck!T(value);
}

auto foo() {
     return forceCheck(42);
}

void main() {
     {
         auto a = foo();
         if(a != 42) { }         // stored values
     }
     {
         if(foo() != 42) { }     // direct access
     }
     {
         foo().ignore();         // explicitly ignore return value
     }
     {
         auto b = foo();         // this one asserts
         foo();                  // as does this one
     }
}

I guess it's reasonably performant; it could be optimized further 
by only adding the `checked` member if assertions are enabled 
(using `version(assert)`).


More information about the Digitalmars-d-learn mailing list