访问 nullptr 怎么可能有效?

How is possible that accessing nullptr works?

我有一个简单的class:

class B
{
public:
    int getData() { return 3; }
};

然后,我用 nullptr 初始化一个指向它的指针:

B *foo{ nullptr };

然后,尝试使用它时,惊喜来了:

int t = foo->getData();

现在 t 是 3。如果不构造 class 怎么可能?是因为getData()没有使用"this"吗?这打破了我对指针的所有认识。

这是预期的行为吗?我在 Visual Studio 2013 年工作。

Is that expected behavior?

不,是UB,一切皆有可能。

Is it because getData() does not use "this"?

是的,它可能会起作用,因为 this 不会在特殊情况下使用,但不能保证。

这是未定义的行为,您正在从nullptr访问一个成员方法。不会定义特定的行为或结果。

虽然在这种情况下;给定 (cppreference):

The keyword this is a prvalue expression whose value is the address of the object, on which the member function is being called.

由于 thisNULL 值没有被取消引用 - 成员方法不是虚拟的并且不访问 this 的任何成员数据 - 它 "seems" 上班。

undefined behavior, so you really should be very scared.

它可能碰巧做了一些事情(在你的 C++ 实现中),因为 getData 函数不是虚拟的并且不使用 B 的任何成员。所以生成的代码不会取消引用空指针。