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

问题描述

对于以下代码段:(或选中https://godbolt.org/z/15bqMj

std::vector<int> v{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,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,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,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,^

这是一个假阳性警告,还是我刚刚在代码中写了一个错误?

解决方法

我刚刚在代码中写了一个错误?

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

这是假阳性警告

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

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

,

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

似乎clang尝试为您的<=>使用<运算符,因此内部实现会向您发出此警告。

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

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...