是否允许向空指针添加零? [英] Is it allowed to add a zero to a null pointer?

查看:69
本文介绍了是否允许向空指针添加零?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道指针算法不允许用于空指针.但想象一下我有这样的事情:

I know that pointer arithmetic is disallowed for null pointers. But imagine I have something like this:

class MyArray {
  int *arrayBegin;  // pointer to the first array item, NULL for an empty array
  unsigned arraySize;   // size of the array, zero for an empty array
public:
  int *begin() const { return arrayBegin; }
  int *end() const { return arrayBegin + arraySize; }  // possible? (arrayBegin may be null)

是否可以(允许)使用上述 end() 实现?还是必须要有:

Is it possible (allowed) to have the above end() implementation? Or is it necessary to have:

  int *end() const { return (arraySize == 0) ? nullptr : (arrayBegin + arraySize); }

要避免使用 nullptr 进行指针运算,因为 arrayBegin 对于空数组为 null(尽管在这种情况下 arraySize 也为零)?

to avoid pointer arithmetic with nullptr because arrayBegin is null for an empty array (despite arraySize also being zero in this case)?

我知道可以存储 int *end; 而不是 unsigned size; 并让大小计算为 end-begin - 但是然后出现了同样的问题:是否允许计算 nullptr - nullptr?

I know it's possible to store int *end; instead of unsigned size; and let size be computed as end-begin - but then comes the same issue: Is it allowed to compute nullptr - nullptr?

我特别喜欢标准参考.

推荐答案

是的,您可以将零添加到空指针并从另一个空指针中减去一个.引用 C++ 标准的加法运算符 [expr.add] 部分:

Yes, you can add zero to the null pointer and subtract one null pointer from another. Quoting Additive operators [expr.add] section of the C++ standard:

当一个整数类型的表达式J与指针类型的表达式P相加或相减时,结果的类型为P代码>.

When an expression J that has integral type is added to or subtracted from an expression P of pointer type, the result has the type of P.

  • 如果 P 的计算结果为空指针值并且 J 计算结果为 0,则结​​果为空指针值.
  • If P evaluates to a null pointer value and J evaluates to 0, the result is a null pointer value.

这篇关于是否允许向空指针添加零?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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