by cpgxiii · 1w ago · 0 comments
Perhaps for a more familiar case where contracts allow greater memory safety: constexpr T& operator[](size_t i) const pre(i < size()); constexpr T& front() const pre(!empty());
or even more commonly: void register_handler(std::unique_ptr<Handler> h) pre(h != nullptr);
int x = 1;
foo(x);
// What values has x?
In C the answer is obvious, in C++ due to the existence of references and the poor way they are designed, it is not anymore.Considering that every other "C family" language community gets by just fine with call sites that look like using references, I think calling this element of references "poorly designed" is quite a stretch.
Amusingly, the Chromium folks found this out firsthand when working on Rust bindings - all of the unnecessary pointer arguments due to the GSG complicated the process.
I think the difference is that with references you can only perform such a check before you create the reference. Pretty sure optimizers can and will elide checks for null references.
As someone who had the displeasure of maintaining a decades-old legacy project that had references initialized and assigned with NULL, I don't agree.
[0]: https://cpp.godbolt.org/z/6ze9ns7cz
bool pointer(int* p) {
return p == nullptr;
}
bool reference(int& r) {
return &r == nullptr;
}
Become pointer(int*):
test rdi, rdi
sete al
ret
reference(int&):
xor eax, eax
ret
When compiled with Clang 23.1.0 and -O1.