0

I have some code and i can't understand is there a UB on dereferencing pointer or not. It works OK, but i have have doubts.

#include <iostream>
#include <cstdlib>

template <class T>
struct NullRef
{
    static T& null(void)
    {
        static T* p(nullptr);
        return *p;
    }
    static bool isNull(const T& t)
    {
        return &t == &null();
    }
};

bool foo(const int& r = NullRef<int>::null()) {
    return NullRef<int>::isNull(r);
}

int main()
{    
    std::cout << "isNull = "<<foo() << std::endl;
    return 0;
}
AlexBG
  • 386
  • 1
  • 7
  • As per the answer in the duplicate: yes, dereferencing that pointer to obtain the l-value returned by the function `null` is undefined behavior. – E_net4 Apr 24 '20 at 14:38
  • 1
    Clang says: runtime error: reference binding to null pointer of type 'int' – eerorika Apr 24 '20 at 14:39
  • 1
    Yes, it is undefined behavior to dereference a nullptr. "(Undefined behavior) works OK" may appear to work okay. Or it may crash. Or it may do something weird. Or it may work okay on your machine, and crash or do something weird on someone else's machine. _Undefined behavior_ is fickle that way. – Eljay Apr 24 '20 at 14:57

0 Answers0