混合索引和指针算术时避免使用C4365,而无需铸造

Avoiding C4365 when mixing index and pointer arithmetic without casting

本文关键字:C4365 指针 索引 混合      更新时间:2023-10-16

我有一个代码库,模板在一个向量中查找一个值,然后使用计算的索引在某个位置处获得一个值。

这是为Visual Studio提供的一些来源的来源:

#pragma once
#pragma warning(disable: 4514)
#pragma warning(disable: 4710) 
#pragma warning(disable: 4189)
#include <vector>
int main(int, char *[])
{
    //contrived example, never mind the non C4365 issues in this code
    //I am aware that this makes not a lot of sense runtime wise
    //This question is about a compiler warning
    int target;
    std::vector<char> first;
    std::vector<long> second;
    auto it = std::find(first.begin(), first.end(), target);
    //Warning C4365 '...': conversion from '...' to '...', signed/unsigned mismatch
    std::size_t pos = it - first.begin(); //from int to std::size_t
    long result = second.at(pos);
    return 0;
}

我对警告C4365特别感兴趣。MSDN有一个条目,还有另一个与此相关的stackoverflow问题。

我知道此std::size_t pos = static_cast<size_t>(it - first.begin());删除了警告。

我的问题是上述查找和获取值是否可以写成,因此不需要造型以避免警告。

编辑:我没有提到此警告在警告级别4和默认情况下。

下面的代码不会生成任何警告,因为您将 int添加到有效的迭代器中。

int main(int, char *[])
{
    //contrived example, never mind the non C4365 issues in this code
    //I am aware that this makes not a lot of sense runtime wise
    //This question is about a compiler warning
    int target;
    std::vector<char> first;
    std::vector<long> second;
    auto it = std::find(first.begin(), first.end(), target);
    auto it2 = second.begin() + ( it - first.begin() );
    long result = *it2;
    return 0;
}