Express "Class argument may not be null" ?

Steven Schveighoffer via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Aug 9 05:52:31 PDT 2017


On 8/8/17 4:00 PM, Andre Kostur wrote:
> On 2017-08-08 12:38 PM, Steven Schveighoffer wrote:
>> On 8/8/17 2:56 PM, ag0aep6g wrote:
>>> 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&)".
>> [snip]
>>>
>>> But you can pass null in a ref parameter:
>>>
>>> ----
>>> void f(ref int x) @safe {}
>>> void main() @safe
>>> {
>>>      int* p = null;
>>>      f(*p);
>>> }
>>> ----
>>
>> Note that C++ also can do this, so I'm not sure the & is accomplishing 
>> the correct goal:
>>
>> void foo(Klass&);
>>
>> int main()
>> {
>>     Klass *k = NULL;
>>     foo(*k);
>> }
>>
>> However, the in contract does actually enforce the requirement.
> 
> To be fair: it cannot be done in C++ without first invoking Undefined 
> Behaviour (such as dereferencing a nullptr).

If your "insurance" that null pointers aren't passed is the threat of 
undefined behavior, then it leaves a lot to be desired.

It's possible, and does happen. The "just don't write bugs" approach 
doesn't scale.

-Steve


More information about the Digitalmars-d-learn mailing list