Are nullptr references undefined behaviour in C++? [duplicate]

戏子无情 提交于 2019-12-04 13:13:20

// 2. dereference a nullptr pointer and pass it as reference

Dereferencing a null pointer is Undefined Behaviour, and so whether you pass it as a reference or by value, the fact is that you've dereferenced it and therefore invoked UB, meaning from that point on all bets are off.

You've already invoked UB here:

int &ir = *ip; //ip is null, you cannot deref it without invoking UB.

Since ir is just a shadow of *ip it will not cause an undefined behavior on its own.

The undefined behavior is using a pointer which points to nullptr_t. I mean using *ip. Therefore

int &ir = *ip;
          ^^^

Causes an UB.

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