Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

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

 help



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.



Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: