I'm having a rather strange warning being reported by clang-tidy 12.0.1. In the following code:
#include <vector>
int main()
{
std::vector<int> v1;
const auto a = v1.begin() + v1.size();
return 0;
}
I see this warning being triggered:
error: narrowing conversion from 'std::vector<int>::size_type' (aka 'unsigned long long') to signed type 'std::_Vector_iterator<std::_Vector_val<std::_Simple_types<int>>>::difference_type' (aka 'long long') is implementation-defined [bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions,-warnings-as-errors]
const auto a = v1.begin() + v1.size();
^
It was my understanding that when operating two integers with the same size but different signedness, the signed integer is converted to unsigned, not the other way around. Am I missing something here?
Since C++20 a simple fix is to use std::sszie
:
const auto a = v1.begin() + std::ssize(v1);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With