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

Why does this code snippet work? How can a nullptr be dereferenced?

本文关键字:取消 引用 何取消 代码 片段 有效 为什么      更新时间:2023-10-16
#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

PS:这段代码片段取自YouTube上的Cherno C++系列。

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

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

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

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