一些基本的指针数学会导致编译器之间产生不明确的结果。
#include <cstdint>
int main()
{
int * test = new int{100};
int * a = nullptr;
auto diff = test - a;
int * test_copy = diff + a;
return *test_copy;
}
https://godbolt.org/z/gvfg1m
这里的问题是指针不指向同一个对象。将运算符+
或运算符-
应用于不属于同一对象的指针是未定义的行为。
测试
来自全局运算符New
。NullPtr
不是全局运算符new
管理的内存的一部分。这也是两个分开的东西。
为了测试这一点,不要将a
设置为nullptr
,而是将其设置为另一个来自全局运算符new
的随机int
。
#include <cstdint>
int main()
{
int * test = new int{100};
int * a = new int{};
auto diff = test - a;
int * test_copy = diff + a;
return *test_copy;
}
https://godbolt.org/z/req74S
现在编译器似乎很高兴。