Search code examples
c++pointersstaticstatic-methodsnullptr

Why does this code snippet work? How can a nullptr be dereferenced?


#include <iostream>

class Singleton {
private:
    static Singleton* s_instance;

public:
    static Singleton& Get() {
        return *s_instance;
    }

    void Hello() {
        std::cout << "Hey Bro" << std::endl;
    }
};

Singleton* Singleton::s_instance = nullptr;

int main() {
    Singleton::Get().Hello();
    return 0;
}

And it prints the output from the member function Hello(). How can a nullptr be dereferenced in the static member function Get()

P.S: This code snippet was taken from the Cherno C++ series on YouTube.


Solution

  • It's undefined behaviour, as StoryTeller says.

    Most probably it "works" because you don't actually use the pointer at the assembly level.

    Member functiors are static functions which take the this pointer. In your member function Hello(), this is not used because you are not accessing any member variables. So the function is actually a void Hello(Singleton* this) {} which is passed a null, but noone uses it, so no crash. There is some similarity when using delete this; in some member function; the members are destructed, but not the function body itself.

    But as said, it's UD, anything can happen. Never rely on such behaviour.