繁体   English   中英

C++ - unsigned long long 到 signed long long 的隐式转换?

[英]C++ - Implicit conversion of unsigned long long to signed long long?

clang-tidy 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();
                                ^

我的理解是,当操作两个大小相同但符号不同的整数时,有符号的 integer 被转换为无符号的,而不是相反。 我在这里错过了什么吗?

要显示所涉及的实际类型:

// 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;
}

由于 C++20 一个简单的解决方法是使用std::sszie

const auto a = v1.begin() + std::ssize(v1);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM