logoalt Hacker News

cpgxiii • last Sunday at 10:42 PM • 3 replies • view on HN

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.


Replies

horseloverthin • last Sunday at 10:56 PM

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

➕ show 1 reply
uecker • yesterday at 6:42 AM

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.
➕ show 2 replies
coliveira • yesterday at 12:46 AM

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.

➕ show 2 replies