1

可能重复:
在 NULL 指针上访问类成员

我知道取消引用 NULL 指针会使程序崩溃或给出未定义的行为。但是以下程序始终打印This is a car出我运行了多少次。在 Linux (g++) 和 AIX (xlc++) 中检查。

#include <iostream>
using namespace std;

class Car
{
public:
    void display(){ cout << "This is a car" << endl; }
};

int main()
{
    Car *c = NULL;
    c->display();
}

当我为类添加一个数据成员并尝试打印它的值时,程序就会崩溃。

class Car
{
     int i;
 public:
     void display(){ cout << "This is a car" << i << endl; }
};

因此,取消引用 NULL 指针并调用不访问类的数据成员的成员函数似乎很好。这真的是一种未定义的行为吗?

4

0 回答 0