Express "Class argument may not be null" ?
    ag0aep6g via Digitalmars-d-learn 
    digitalmars-d-learn at puremagic.com
       
    Tue Aug  8 11:56:36 PDT 2017
    
    
  
On 08/08/2017 08:34 PM, Johan Engelen wrote:
>    How would you express the function interface intent that a reference 
> to a class may not be null?
> For a function "void foo(Klass)", calling "foo(null)" is valid. How do I 
> express that that is invalid? (let's leave erroring with a compile error 
> aside for now)
> 
> Something equivalent to C++'s pass by reference: "void foo(Klass&)".
A contract might be the best you can do:
----
void foo(Klass k)
in { assert(k !is null); }
body {}
----
Or throw an exception.
> (note: I mean D classes, for structs "ref" works)
But you can pass null in a ref parameter:
----
void f(ref int x) @safe {}
void main() @safe
{
     int* p = null;
     f(*p);
}
----
    
    
More information about the Digitalmars-d-learn
mailing list