为什么此代码片段有效?如何取消引用空点?
Why does this code snippet work? How can a nullptr be dereferenced?
#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,任何事情都可能发生。永远不要依赖这种行为。
相关文章:
- C++取消引用指针.为什么会发生变化
- 使用取消引用的指针的多态性会产生意外的结果.为什么?
- 取消引用运算符不能重载
- 在他自己的方法中,有可能将一个对象取消引用到另一个对象吗
- C++ 关于指针取消引用的技术问题
- 没有取消引用/解包对象的标准方法?
- 列表 iter 不取消引用 使用列表进行插入排序
- 在这个函数中是有缺陷的,因为取消引用 null 是无效的,所以我想更改代码
- 取消引用结束指针到数组类型的一个
- 取消引用向量时出现问题
- 取消引用指向整数的指针时获得不同的结果
- C++:取消引用十六进制值,有点语法问题
- C/C++ 取消引用错误:在空检查之前取消引用
- 取消引用后C++空测试
- 立即取消引用unique_ptr
- 如何在不使用临时变量的情况下取消引用返回指针的函数的返回值?
- 取消引用 void 指针以将值分配给结构
- boost_multi_index迭代器取消引用给出常量
- 矢量迭代器不能与 std::shared_ptr<> 取消引用
- C++我们可以取消引用此指针吗?如果是这样,那么如何,如果不是,那为什么?