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

问题描述 投票:0回答:1
#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 ++系列。

#include 类Singleton {私有:静态Singleton * s_instance;公开:静态Singleton&Get(){return * s_instance; } void Hello(){std :: ...

c++ pointers static static-methods nullptr
1个回答
1
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.