c++ - 两个 nullptr 值相减保证为零?

标签 c++ c++11

C++ 标准是否保证,如果我有两个相同类型的指针,其值等于 nullptr,那么这些指针之间的差值等于 0?

在伪数学符号中,以下谓词是否成立?

ForAll x ForAll y (x == nullptr)^(y == nullptr) -> (x - y == 0)

我能想到的最简单的代码示例是:

int* x = nullptr;
int* y = nullptr;
assert(x - y == 0);

我想这可以归结为:是否有可能有一个有效的 C++ 标准实现,其中有 nullptr 的多个位表示,只比较为相等,因为相等运算符做了一些魔术?

最佳答案

是的,这是有效的。它在 C 中是未定义的,但 C++ 为 - 运算符添加了一个特殊的异常(exception)来定义行为。

5.7 Additive operators [expr.add]

7 If the value 0 is added to or subtracted from a pointer value, the result compares equal to the original pointer value. If two pointers point to the same object or both point one past the end of the same array or both are null, and the two pointers are subtracted, the result compares equal to the value 0 converted to the type std::ptrdiff_t.

关于c++ - 两个 nullptr 值相减保证为零?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27681633/

相关文章:

c++ - 从没有对象的 Objective C 调用特定的 C++ 方法

c++ - G++-4.7.0 递归类型别名的内部编译器错误分段故障

c++ - 如何从调用表达式中获取函数的类型?

c++ - 我可以确保 RVO 用于重新解释的值吗?

C++ 11 花括号

c++ - 如何避免在类的构造函数中需要提供两次模板?

c++ - 在独立的 Xcode playground 中运行 c 或 c++ 代码

c++ - 从输入文件中读取十六进制列

c++ - 如何返回 fstream (C++0x)

c++ - 什么是 "terminate called after throwing an instance of ' std::bad_weak_ptr' “在我使用shared_ptr之后