混合索引和指针算术时避免使用C4365,而无需铸造
Avoiding C4365 when mixing index and pointer arithmetic without casting
我有一个代码库,模板在一个向量中查找一个值,然后使用计算的索引在某个位置处获得一个值。
这是为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;
}
相关文章:
- 1d 智能指针不适用于语法 (*)++
- 在C#中处理C++指针而不使用unsafe的最佳方法
- 为什么使用 "this" 指针调用派生成员函数?
- 函数向量_指针有不同的原型,我可以构建一个吗
- 使用指针从C++中的数组中获取最大值
- 助记符和指向成员语法的指针
- 嵌入方指针压缩已禁用
- 数组的指针从不分段故障
- C++ 指针的内存地址和指向数组的内存地址如何相同?
- 何时在引用或唯一指针上使用移动语义
- QMetaObject invokeMethod的基于函数指针的语法
- 如何从 std::atomic 中提取指针 T<T>?
- 如何在 C# 中映射双 C 结构指针?
- C++将浮点指针值舍入为小数位数
- 为什么++(*p)更改指针值
- 调整大小后指向元素值的指针unordered_map有效?
- 正在将指针转换为范围
- 使用指向成员的指针将成员函数作为参数传递
- 将OpenCV C++重写为EmguCV C#-如何使用指针
- 混合索引和指针算术时避免使用C4365,而无需铸造