gpt4 book ai didi

c++ - 是否可以将零添加到空指针?

转载 作者:行者123 更新时间:2023-12-04 07:48:14 25 4
gpt4 key购买 nike

我知道对于空指针不允许使用指针算术。但是想象一下我有这样的事情:

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()实现?还是必须具有:
  int *end() const { return (arraySize == 0) ? nullptr : (arrayBegin + arraySize); }

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

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

我特别喜欢标准引用书。

最佳答案

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

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.

  • If P evaluates to a null pointer value and J evaluates to 0, the result is a null pointer value.

关于c++ - 是否可以将零添加到空指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59409034/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com