下面是一段c++代码:
class Metadata : public MetaspaceObj {
void print_value_on_maybe_null(outputStream* st) const {
if (this == NULL)
st->print("NULL");
else
print_value_on(tty);
}
}
我只是想知道 C++ 对象中的“this”怎么可能为 NULL。有可能吗?
上面的代码摘自jdk8/openjdk/hotspot/src/share/vm/oops/metadata.hpp。
最佳答案
在 C++ 中,您实际上可以在 NULL
指针上取消引用和调用成员函数。
考虑:
Metadata* pointer = nullptr;
pointer->print_value_on_maybe_null(...);
上面的代码是有效的 C++ 代码,可以正常编译。这样做的问题是它会导致 undefined behavior .
回到问题中的代码,我认为过去某个时候,某个地方存在一个错误,导致在空指针上调用成员函数,而不是尝试查找并修复根本原因对于这个问题,作者只是添加了对 this == NULL
的检查。
关于java - C++ 类中 'this' 指针可以为空吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25839843/