C++ standard: dereferencing NULL pointer to get a reference? [duplicate]

怎甘沉沦 提交于 2020-01-04 05:21:37

问题


I'm wondering about what the C++ standard says about code like this:

int* ptr = NULL;
int& ref = *ptr;
int* ptr2 = &ref;

In practice the result is that ptr2 is NULL but I'm wondering, is this just an implementation detail or is this well defined in the standard?
Under different circumstances a dereferencing of a NULL pointer should result in a crash but here I'm dereferencing it to get a reference which is implemented by the compiler as a pointer so there's really no actual dereferencing of NULL.


回答1:


Dereferencing a NULL pointer is undefined behavior.

In fact the standard calls this exact situation out in a note (8.3.2/4 "References"):

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 an aside: The one time I'm aware of that a NULL pointer can be "dereferenced" in a well-defined way is as the operand to the sizeof operator, because the operand to sizeof isn't actually evaluated (so the dereference never actually occurs).




回答2:


Dereferencing a NULL pointer is explicitly undefined behaviour in the C++ standard, so what you see is implementation specific.

Copying from 1.9.4 in the C++0x draft standard (similar to previous standards in this respect):

Certain other operations are described in this International Standard as undefined (for example, the effect of dereferencing the null pointer). [Note: this International Standard imposes no requirements on the behavior of programs that contain undefined behavior. - end note]




回答3:


Dereferencing a NULL pointer is undefined behaviour. You should check if a value is NULL before dereferencing it.




回答4:


For completeness, this: http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#232 talks specifically about this issue.




回答5:


int& ref = *ptr;

The above statement doesn't actually dereference anything. So there's no problem until you use the ref (which is invalid).



来源:https://stackoverflow.com/questions/40216965/dereferencing-a-null-pointer-to-a-reference-which-is-unused-is-this-also-undef

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!