Hacker News new | ask | show | jobs
by cpgxiii 6 days ago
If you're going to rewrite a bunch of C++ to add contracts to assert that your pointer arguments are non-null ... you could, I don't know, just use references instead, the exact construct we have had for decades to express this. If you're cargo-culting the GSG so much you're unwilling to use references appropriately I seriously doubt you are also going to replace whatever existing "pointer argument x is non-null" checks you use with a brand-new contracts mechanism.
3 comments

There are many common places where this pointer case comes up and using references is simply not an option ( i.e plugin/FFI boundaries, dlsym callbacks, externed C). You will have a very bad time doing any systems programming, for example, if you live by the dogma of shaking your fist at raw pointers and saying use refs instead!

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);

Yes, I am distinctly over-simplifying things. There certainly are cases where pointers are appropriate, but I suspect anyone doing this responsibly already has the necessary non-null checks idiomatic to their codebase, and I am very dubious that anyone doing so irresponsibly is going to jump straight to contracts. I only mention the GSG because in the codebases I regularly deal with my experience is that the overwhelming majority of non-nullable pointer arguments appear in cases that adherence to the GSG has created, rather than cases where it is actually necessary for the API.
References hide important semantic information:

    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.
What's wrong with checking the signature of foo to see what it does?
Having to check in the first place.
I understand that doing a mouse over in the IDE is something too advanced. /s
There is a huge different between having to actively explore all variables to find out what is behind them to simple looking at the code.
Yeah, that is what happens when one eschews modern IDE tooling, more work for easy stuff.
Except for any codebase of meaningful complexity you end up with functions that mix value and pointer variables, and whatever "obvious" signal you get out of the simple cases disappears into the noise. At the end of the day there is no replacement for understanding the signature and behavior of the function that is being called.

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.

Specially coming from a language that after 50 years still doesn't have slices to fix their strings and arrays, something that Dennis Ritchie proposed when he still cared about the standard.
I use slices in C, I just have to define them myself.
Yeah, what a great solution, I can also use slices in Assembly, one just needs a proper macro processor like MASM and TASM from the 1990s.
yes, and if you assembly this is fine solution. Also there is no fundamental reason C++'s library types using templates are better to macros. The mechanism is basically the same.
References are not a magical spell that guarantees a pointer is non-null. While they help avoid this, because of the way C++ behaves it may result in a null object as well, so a run-time check is still needed.
What references avoid is the unnecessary addition of nullability, not nullability at the source. They also convey that non-nullability to the compiler and user of your API directly, rather than hoping that point-of-use null checks convey the same thing. You still need null checks if you have nullable items, but better to localize those checks specifically where needed than scatter them across your codebase.

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.

> While they help avoid this, because of the way C++ behaves it may result in a null object as well, so a run-time check is still needed.

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.

> 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.

Do you mind elaborating? Modern compilers will definitely optimize out checks for null references [0] (but probably aren't guaranteed to), so checking after the fact seems like an iffy proposition to me at best.

[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.
I read the quote as "I have old code filled with bugs and UB. Using references don't magically solve the bugs"
In that case I think I'd agree that references are not a silver bullet, especially with modern optimizing compilers.