2
#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.

  • 1
    See this https://stackoverflow.com/questions/2533476/what-will-happen-when-i-call-a-member-function-on-a-null-object-pointer . As for the Youtube tutorial, it may be better to ditch it in favor of a good book https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list – StoryTeller - Unslander Monica May 17 '20 at 11:53
  • What do you mean by "work"? On my machine, this code crashes. – Eljay May 17 '20 at 12:42
  • 1
    Dereferencing `nullptr` causes undefined behaviour. The meaning of "undefined" in C++ is essentially "the C++ standard does not place any constraints on what happens". Practically, that doesn't require a runtime error, or anything else - it is within the bounds of undefined behaviour that it can seem to "work" - for any definition a programmer may place on "work". – Peter May 17 '20 at 13:02

1 Answers1

3

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.

Michael Chourdakis
  • 10,345
  • 3
  • 42
  • 78