Author Topic: Explicit non-null-ness  (Read 21 times)


  • Full Member
  • ***
  • Posts: 231
    • View Profile
Explicit non-null-ness
« on: February 02, 2019, 12:28:24 PM »
I suggest we reuse & arg to mean a pointer that is guaranteed to be non-null.

Consider the following methods:

Code: [Select]
Foo& foo();
Foo* foo2();
void bar(Foo& f);
void bar2(Foo* f);

Unlike in C++, both Foo& and Foo* are pointer, the former guaranteed to be not null.

Code: [Select]
Foo *f1 = foo(); // Non null to nullable ok
Foo &f2 = foo2(); // Nullable to non null not allowed

A check allows conversion:

Code: [Select]
Foo *f = foo2();
Foo &f2 = f;


Code: [Select]
Foo *f = foo2();
Foo &f2 = f ? f : foo();

With the elvis operator:

Code: [Select]
Foo &f = foo2() ?: foo();

Using pointer without nullcheck is a warning:

Code: [Select]
Foo* f = foo2();
return f.a; // warn, f may be null.

Solution is adding the assert test, or supress null warning with an attribute

Code: [Select]
Foo *f = foo2();
return f.a @(notnull);