警告:比较迭代器时零作为空指针常量

warning: zero as null pointer constant while comparing iterators

如下代码段:(或勾选https://godbolt.org/z/15bqMj

std::vector<int> v{1,2,1,2,1,2};
for (auto it = v.cbegin(); (it = find_if(it, v.cend(), somePredicate)) < v.cend(); ++it) {
    std::cout << *it << std::endl;
}

我收到编译器的警告(clang 11-std=c++20 -Wzero-as-null-pointer-constant):

warning: zero as null pointer constant [clang-diagnostic-zero-as-null-pointer-constant]
  for (auto it = v.cbegin(); (it = find_if(it, v.cend(), somePredicate)) < v.cend(); ++it) {
                                                                         ^
/usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/bits/stl_iterator.h:1080:5: note: while rewriting comparison as call to 'operator<=>' declared here
    operator<=>(const __normal_iterator<_IteratorL, _Container>& __lhs,
    ^
note: this fix will not be applied because it overlaps with another fix
warning: use nullptr [hicpp-use-nullptr,modernize-use-nullptr]
  for (auto it = v.cbegin(); (it = find_if(it, v.cend(), somePredicate)) < v.cend(); ++it) {
                                                                         ^
note: this fix will not be applied because it overlaps with another fix
warning: zero as null pointer constant [-Wzero-as-null-pointer-constant]
  for (auto it = v.cbegin(); (it = find_if(it, v.cend(), somePredicate)) < v.cend(); ++it) {
                                                                         ^
                                                                         nullptr
/usr/bin/../lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/bits/stl_iterator.h:1080:5: note: while rewriting comparison as call to 'operator<=>' declared here
    operator<=>(const __normal_iterator<_IteratorL, _Container>& __lhs,
    ^

这是一个误报警告,还是我只是在我的代码中写了一个错误?

通常仅使用 ==!= 比较迭代器。据我所知,没有为迭代器定义其他比较运算符。

看起来 clang 试图为您的 < 使用 <=> 运算符,因此内部实现给了您这个警告。

编辑:随机访问迭代器应定义所有比较运算符,并且由于 vector 应 return 随机访问迭代器,因此 clang 中似乎存在错误。

I just wrote a bug in my code?

不,您的代码中没有错误。

Is this a false-positive warning

可能是的。它可能是您隐式使用的标准库函数的实现的 true-positive,但如果是这种情况,则警告消息不完整,因为它无法显示使用 0 的代码。

这也应该是一个错误,因为标准库中不应显示警告 headers。