4 ms·
Compilers can give us a warm feeling when they help us enforce invariants at compile time, but those invariants can only be applied on information known at comp
by halayli 11y ago
Compilers can give us a warm feeling when they help us enforce invariants at compile time, but those invariants can only be applied on information known at compile time. pointer values cannot be known at compile time.
not_null gives you the illusion of creating compile time invariants based on dynamic values. But that's impossible. You can still pass a nullptr to a not_null parameter indirectly which will assert at runtime. It just prevents a user from passing nullptr directly as a function argument. It provides no advantage to pass by reference. If you pass a null reference (you gotta go out of your way to do that), it will fail at runtime just like not_null. not_null does provide a consistent way of doing assert(value != nullptr) but an assert is clearer imo, not_null hides the assert away from the programmer and adds ambiguity. You can forget to assert just like you can forget to specify a parameter as not_null.
int *x = nullptr;
int **value = &x;
func(*value);
This will compile just fine, but will assert at runtime.
If the program state cannot proceed when one of the functions is passed a nullptr then assert in the function and make it clear, otherwise check for nullptr condition and proceed accordingly. You can forget to do that just like you can forget to increment a value.