为什么作为 "reference of value of pointer set to nullptr" 返回的对象是有效对象(单例)(C++)?
Why object returned as "reference of value of pointer set to nullptr" is a valid object (singleton) (C++)?
我最近在 C++ 教程中看到示例不完整的单例 class 代码,我自己无法解释它为什么有效。
#include <iostream>
class Singleton
{
private:
static Singleton* s_Instance;
public:
static Singleton& Get()
{
// I put this check to see if it really is nullptr
if (s_Instance == nullptr)
std::cout << "nullptr" << std::endl;
return *s_Instance;
}
void Hello()
{
std::cout << "Hello" << std::endl;
}
};
Singleton* Singleton::s_Instance = nullptr;
int main()
{
Singleton::Get().Hello();
}
现在这显然不是真正的单例,但这不是重点。
我不明白为什么要返回设置为 nullptr
returns 的指针的值 class 的实例以及为什么可以获得 nullptr
。还是我遗漏了其他事情?
我最近在 C++ 教程中看到示例不完整的单例 class 代码,我自己无法解释它为什么有效。
#include <iostream>
class Singleton
{
private:
static Singleton* s_Instance;
public:
static Singleton& Get()
{
// I put this check to see if it really is nullptr
if (s_Instance == nullptr)
std::cout << "nullptr" << std::endl;
return *s_Instance;
}
void Hello()
{
std::cout << "Hello" << std::endl;
}
};
Singleton* Singleton::s_Instance = nullptr;
int main()
{
Singleton::Get().Hello();
}
现在这显然不是真正的单例,但这不是重点。
我不明白为什么要返回设置为 nullptr
returns 的指针的值 class 的实例以及为什么可以获得 nullptr
。还是我遗漏了其他事情?