gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 10:02:38 25 4
gpt4 key购买 nike

#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 所说,这是未定义的行为。

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

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

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

关于c++ - 为什么这个代码片段有效?如何取消引用 nullptr?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61851329/

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