其中哪些将创建一个空指针? [英] Which of these will create a null pointer?

查看:278
本文介绍了其中哪些将创建一个空指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

标准说,取消引用空指针会导致未定义的行为。但是什么是空指针?在下面的代码中,我们称之为空指针:

The standard says that dereferencing the null pointer leads to undefined behaviour. But what is "the null pointer"? In the following code, what we call "the null pointer":

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 ++标准,编译时空指针和运行时之间是否有区别?

My thought is that dereferencing of the null pointer takes place only in the last case. Am I right? Is there difference between compile time null pointers and runtime according to C++ Standard?

推荐答案

只有第一个和最后一个是空指针。其他是 reinterpret_cast 的结果,因此对实现定义的指针值进行操作。它们的行为是否未定义取决于在所转换的地址是否有对象。

Only the first and the last are null pointers. The others are results of reinterpret_cast and thus operate on implementation defined pointer values. Whether the behavior is undefined for them depends on whether there is an object at the address you casted to.

这篇关于其中哪些将创建一个空指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆