Discarded return values

Jonathan M Davis newsgroup.d at jmdavisprog.com
Tue Jan 30 11:36:25 UTC 2018


On Tuesday, January 30, 2018 10:49:54 Simen Kjærås via Digitalmars-d-learn 
wrote:
> Is there a way to get a compile error when returning a temporary
> from a function and then not assigning it to a variable or
> passing it to a different function? E.g:
>
> struct S {
>      int[] a;
>      void morph() {}
> }
>
> @warnOnDiscard
> S foo() {
>      return S([1,2,3]);
> }
>
> unittest {
>      auto a = foo(); // Fine, assigned to variable.
>      bar(foo());     // Fine, passed to other function.
>      foo();          // Error: return value is discarded.
>      foo().morph();  // Error: return value is discarded.
> }
>
> I know that pure functions give errors when their results are
> discarded, but in this case foo() might not be pure.

Well, the first problem is that you simply can't warn or give an error about
that if the function isn't pure, because if it isn't pure, then it could be
doing work, and it might be perfectly okay for the return value to be
ignored. So, while it might make sense for some functions, it wouldn't make
sense for others, and unless it never makes sense to ignore the return
value, the compiler can't reasonably warn about it.

Having an attribute that tells the compiler that it's not okay to ignore the
return value for that specific function could solve that problem, because it
would give the programmer a way to tell the compiler that that particular
function is not doing work such that it's reasonable to ignore the return
value, but that brings up the second problem which is that no such attribute
exists and that there is no way to create attributes to tell the compiler to
warn about something. UDAs are simply there to be used by code introspection
done by user code. The compiler itself doesn't do anything interesting with
them. So, in order to get something like that, a DIP would be required.

IIRC, the Weka guys wanted to be able to have attributes tell the compiler
stuff so that it could yell at the programmer when appropriate, so I think
that there is some interest in this area, but I have no idea how such a
thing would be implemented. New built-in attributes that warn about specific
stuff could certainly be added, but in each case, there would have to be a
solid enough argument as to why it was worth adding that further
complication to the language. I have no idea what the chances of being
accepted would be for a DIP specifically for an attribute to warn if the
return value is ignored, but you can certainly create such a DIP if you feel
strongly enough about it and feel that you can argue it well.

- Jonathan M Davis




More information about the Digitalmars-d-learn mailing list