Is there a platform or situation where dereferencing (but not using) a null pointer to make a null reference will behave badly?

前端 未结 6 1632
春和景丽
春和景丽 2020-12-03 02:45

I\'m currently using a library that uses code like

T& being_a_bad_boy()
{
    return *reinterpret_cast(0);
}

to make a refere

6条回答
  •  温柔的废话
    2020-12-03 03:40

    I don't know if this is problems enough for you, or near enough to your "use case", this crashes for me in gcc (on x86_64) :

    int main( )
    {
        volatile int* i = 0;
        *i;
    }
    

    That said, we should keep in mind that it is always UB, and compilers might change their mind later, so that today it works, tomorrow not.

    Another not so obvious bad thing will happen when you call a virtual function on a null pointer (due to usually being implemented via vptr to vtable), and as such of course this applies to the (in standard C++ not existing) null reference.

    Btw. I even heard that architectures exist, where even copying around a non-null pointer to invalid memory will trap, maybe there exists also some out there which makes a distinction between pointer and reference.

提交回复
热议问题