Is using NULL references OK?

前端 未结 7 1417
一整个雨季
一整个雨季 2020-12-05 20:37

I came across this code:

void f(const std::string &s);

And then a call:

f( *((std::string*)NULL) );

A

7条回答
  •  情歌与酒
    2020-12-05 20:55

    No. It is undefined behaviour and can lead to code to do anything (including reformatting you hard disk, core dumping or insulting your mother).

    If you need to be able to pass NULL, then use pointers. Code that takes a reference can assume it refers to a valid object.


    Addendum: The C++03 Standard (ISO/IEC 14882, 2nd edition 2003) says, in §8.3.2 "References", paragraph 4:

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

    [Bold added for emphasis]

提交回复
热议问题