为什么这个代码片段有效?如何取消引用 nullptr?

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;
}

并打印成员函数 Hello() 的输出。如何在静态成员函数 Get()

中取消引用 nullptr

P.S:此代码片段摘自 YouTube 上的 Cherno C++ 系列。

正如 StoryTeller 所说,这是未定义的行为。

很可能是 "works" 因为您实际上并没有 在程序集级别使用 指针。

成员函数是采用this指针的静态函数。在您的成员函数 Hello() 中, this 未被使用,因为您没有访问任何成员变量。所以这个函数实际上是一个 void Hello(Singleton* this) {} 传递了一个空值,但是没有人使用它,所以没有崩溃。在某些成员函数中使用 delete this; 时有一些相似之处;成员被破坏,但函数体本身没有被破坏。

但正如所说,这是UD,任何事情都有可能发生。永远不要依赖这种行为。