gpt4 book ai didi

c++ - 为什么作为 "reference of value of pointer set to nullptr"返回的对象是有效对象(单例)(C++)?

转载 作者:行者123 更新时间:2023-11-28 04:09:17 26 4
gpt4 key购买 nike

我最近在 C++ 教程中看到示例不完整的单例类代码,我自己无法解释它为什么有效。

#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 的指针的值会返回该类的实例以及为什么可以获取 nullptr 的值.还是我遗漏了其他事情?

最佳答案

关于c++ - 为什么作为 "reference of value of pointer set to nullptr"返回的对象是有效对象(单例)(C++)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58162042/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com