该标准指出,解除引用空指针会导致未定义的行为。但什么是“空指针”?在下面的代码,我们称之为“空指针”:其中哪些会创建一个空指针?
struct X
{
static X* get() { return reinterpret_cast<X*>(1); }
void f() { }
};
int main()
{
X* x = 0;
(*x).f(); // the null pointer? (1)
x = X::get();
(*x).f(); // the null pointer? (2)
x = reinterpret_cast<X*>(X::get() - X::get());
(*x).f(); // the null pointer? (3)
(*(X*)0).f(); // I think that this the only null pointer here (4)
}
我的想法是,空指针的解引用仅发生最后一例。我对吗?根据C++标准,编译时空指针和运行时是否有区别?
这不是一个家庭作业。 C++标准没有太多关于解引用空指针的信息。我只是想知道。 – 2010-03-24 22:41:10
我在这里的答案的第一部分谈到了解引用空指针:http://stackoverflow.com/questions/2474018/when-does-invoking-a-member-function-on-a-null-instance-result-in- undefined-behav(我爱这个问题) – GManNickG 2010-03-24 22:43:46