如何避免 64 位 C++ 中 size_t 和 int 类型的问题构建?
今天我第一次对我的项目进行 64 位构建。基本上它编译、链接和运行都正常,除了警告抱怨新的 64 位 size_t 类型和简单 int 类型之间不兼容。这主要发生在我的代码中这样的情况下:
void func(std::vector<Something> &vec)
{
int n = vec.size();
for (int i=0; i < n; i++)
{
....vec[i]....
}
}
这很容易修复,我读到一篇文章说应该使用 size_t 或 ptrdif_t 作为循环索引。但遇到这样的情况我能做什么呢?
void outsideLibraryFunc(int n);
void func(std::vector<Something> &vec)
{
int n = vec.size();
outsideLibraryFunc(n);
}
我无法更改外部库的函数声明,它需要一个 int 类型的参数,并且我需要向它传递向量元素的数量。除了禁用编译器警告之外我还能做什么?
Today I made a 64bit build of my project for the first time. Basically it compiled, linked and ran ok, except for warnings complaining about incompatibility between the new, 64bit size_t type and the simple int type. This mostly occurs in situations like this in my code:
void func(std::vector<Something> &vec)
{
int n = vec.size();
for (int i=0; i < n; i++)
{
....vec[i]....
}
}
This is quite easy to fix, and I read an article saying one should rather use size_t or ptrdif_t as loop indices. But what can I do in a situation like this?
void outsideLibraryFunc(int n);
void func(std::vector<Something> &vec)
{
int n = vec.size();
outsideLibraryFunc(n);
}
I can't change the outside library's function declaration, which expects an argument of type int, and I need to pass it the number of the vector elements. What can I do other than disabling the compiler warnings?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
显式转换为
int
,例如,它不会消除将
size_t
转换为int
时出现的任何潜在问题,但它确实告诉编译器知道您是故意进行转换的,并且它不会警告您。Do an explicit cast to
int
, e.g.It doesn't eliminate any of the potential problems with converting
size_t
toint
, but it does tell the compiler that you're doing the conversion on purpose, and it won't warn you about it.投了吗?说真的,如果您无法更改外部库,那么您无能为力。为了更加安全,请检查是否溢出。
Cast it? Seriously if you can't change the external library, there is not much you can do. To be extra safe check for overflow.