General Category > Ideas
Explicit non-null-ness
(1/1)
lerno:
I suggest we reuse & arg to mean a pointer that is guaranteed to be non-null.
Consider the following methods:
--- Code: ---Foo& foo();
Foo* foo2();
void bar(Foo& f);
void bar2(Foo* f);
--- End code ---
Unlike in C++, both Foo& and Foo* are pointer, the former guaranteed to be not null.
--- Code: ---Foo *f1 = foo(); // Non null to nullable ok
Foo &f2 = foo2(); // Nullable to non null not allowed
--- End code ---
A check allows conversion:
--- Code: ---Foo *f = foo2();
assert(f);
Foo &f2 = f;
--- End code ---
Or:
--- Code: ---Foo *f = foo2();
Foo &f2 = f ? f : foo();
--- End code ---
With the elvis operator:
--- Code: ---Foo &f = foo2() ?: foo();
--- End code ---
Using pointer without nullcheck is a warning:
--- Code: ---Foo* f = foo2();
return f.a; // warn, f may be null.
--- End code ---
Solution is adding the assert test, or supress null warning with an attribute
--- Code: ---Foo *f = foo2();
return f.a @(notnull);
--- End code ---
bas:
In C++ a reference is also a pointer that's 'guaranteed' to be non-null. This can work because a function in C++ can return
an object itself that's turned into a reference. I don't see how this could work in C because C doesn't have copy-constructors etc.
lerno:
Semantic analysis can guarantee non-nullness. Don't confuse it with C++, it's just borrowing the operator. int &a means int *a @(non-null).
Navigation
[0] Message Index
Go to full version