我有一个奇怪的警告是由clang 12.0.1报告的。在以下代码中:
#include <vector>
int main()
{
std::vector<int> v1;
const auto a = v1.begin() + v1.size();
return 0;
}我看到这一警告被触发:
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();
^我的理解是,当操作两个大小相同但符号不同的整数时,有符号整数被转换为无符号,而不是相反。我是不是漏掉了什么?
发布于 2021-12-08 13:34:39
要显示所涉及的实际类型:
// Operator+ accepts difference type
// https://en.cppreference.com/w/cpp/iterator/move_iterator/operator_arith
// constexpr move_iterator operator+( difference_type n ) const;
#include <type_traits>
#include <vector>
#include <iterator>
int main()
{
std::vector<int> v1;
auto a = v1.begin();
auto d = v1.size();
// the difference type for the iterator is a "long long"
static_assert(std::is_same_v<long long, decltype(a)::difference_type>);
// the type for size is not the same as the difference type
static_assert(!std::is_same_v<decltype(d), decltype(a)::difference_type>);
// it is std::size_t
static_assert(std::is_same_v<decltype(d), std::size_t>);
return 0;
}发布于 2021-12-08 14:37:03
由于C++20,一个简单的修复就是使用std::sszie
const auto a = v1.begin() + std::ssize(v1);https://stackoverflow.com/questions/70275235
复制相似问题