如何解决警告:比较迭代器时,零为空指针常量
对于以下代码段:(或选中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中似乎存在错误。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。