Search code examples
c++nullpointerexceptionnullptr

Throwing a NullPointerException in C++


Is it possible to let C++ throw a NPE when calling a method on a nullptr object, instead of going in undefined behaviour? I could create a handler for a SEGFAULT signal but this would be realy dangerous, because not every SEGFAULT is a NullPointerException. If i have to do it via just checking in an if clause, is there a efficiant way to do so? Maybe also on compiletime?


Solution

  • Yes you can but its not really a good idea (you should not be handling pointers anyway, in modern C++ pointers are held inside objects that manage their lifespan).

    You can always define a class that holds the pointer. Then when you try and use operator->() it will throw if the held pointer is nullptr.

    template<typename T>
    class ThrowingUniquePtr
    {
         T*   ptr;
         public:
            // STUFF to create and hold pointer.
    
            T* operator->()
            {
                if (ptr) {
                    return ptr;
                }
                throw NullPointerException; // You have defined this somewhere else.
            }
    };
    
    class Run
    {
        public:
            void run() {std::cout << "Running\n";}
    };
    int main()
    {
        ThrowingUniquePtr<Run>    x(new Run);
        x->run();  // will call run.
    
        ThrowingUniquePtr<Run>    y(nullptr);
        y->run();  // will throw.
    }