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

How do C++ references not protect you from NULL ?

From the standard:

> A reference shall be initialized to refer to a valid object or function. [Note: in particular, a null reference cannot exist in a well-defined program, because the only way to create such a reference would be to bind it to the “object” obtained by dereferencing a null pointer, which causes undefined behavior. As described in 9.6, a reference cannot be bound directly to a bit-field. ]



Better try instead of reading standards (and inevitably misreading, or reading differently than compiler authors)...

    #include <stdio.h>
    void test(int& x)
    {
        printf("Hello, world\n"); fflush(stdout);
        printf("and the number is: %d\n", x);
    }
    int main(void)
    {
        int *x = NULL;
        test(*x);
        return 0;
    }
It's just a syntactic discipline. Null references are undefined in C++, just as NULL dereferences are undefined in C.




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

Search: