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

前端 未结 6 1654
春和景丽
春和景丽 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

    The important thing to remember is that you have a contract with your users. If you're trying to return a reference to a null pointer, undefined behavior is now part if your function's interface. If your users are all prepared to accept this, then that's on them... but I would try to avoid it if at all possible.

    If your code can result in an invalid object, then either have it return a pointer (preferably a smart pointer, but that's another discussion), use the null object pattern mentioned above (boost::optional may be useful here), or throw an exception.

提交回复
热议问题