nullptr 和指针算法

The nullptr and pointer arithmetic

考虑到以下代码,对 nullptr 进行指针运算是否安全?

我假设将任何偏移量添加到 nullptr 会导致另一个 nullptr,到目前为止 MSVC 产生了我预期的结果,但是我有点不确定是否使用 nullptr 之类的这是安全的:

float * x = nullptr;

float * y = x + 31; // I assume y is a nullptr after this assigment

if (y != nullptr)
{
  /* do something */
}

您没有定义 "safe" 对您意味着什么,但无论如何,您提出的代码具有未定义的行为。指针运算只允许在指向数组对象的指针值上,或者可能指向数组的尾数。 (出于此规则的目的,非数组对象被视为一个元素的数组。)

由于空指针永远不是对象的地址或对象的地址,因此您的代码永远不会有明确定义的行为。

不,向 nullptr 添加偏移量不会导致 nullptr。这是未定义的行为。

... is it safe to do pointer arithmetic on nullptr?

不,nullptr 上的算术定义不明确,因为它本身不是指针类型(但存在所有指针类型到 NULL 值的转换)。

See here;

std::nullptr_t is the type of the null pointer literal, nullptr. It is a distinct type that is not itself a pointer type or a pointer to member type.


一般来说,任意指针运算(即使是 NULL 值)几乎肯定会导致问题 - 您没有分配该内存 - 尝试读取或写入不属于您。

出于比较目的(例如,最后一个),你会没事的,但否则你的代码将导致未定义的行为。

如需进一步阅读,请参阅 undefined behavior 上的维基百科。

is it safe to do pointer arithmetic on nullptr? 

C++ nullptr上定义了两种操作。对于 :

float * x=nullptr;
float * y=nullptr;
  1. x +/- 0 = x

  2. x-y=0 //note x and y have the same type

你不能对没有定义的东西做出假设,所以你不应该这样做。