简体   繁体   English

如何避免64位C ++版本中size_t和int类型的问题?

[英]How to avoid problems with size_t and int types in 64bit C++ builds?

Today I made a 64bit build of my project for the first time. 今天我第一次制作了64bit的项目版本。 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. 基本上它编译,链接并运行正常,除了抱怨新的64位size_t类型和简单int类型之间不兼容的警告。 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. 这很容易修复,我读了一篇文章说应该使用size_t或ptrdif_t作为循环索引。 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. 我无法更改外部库的函数声明,它需要一个int类型的参数,我需要传递向量元素的数量。 What can I do other than disabling the compiler warnings? 除了禁用编译器警告外,我还能做些什么?

Do an explicit cast to int , eg int进行显式转换,例如

void outsideLibraryFunc(int n);

void func(std::vector<Something> &vec)
{
    outsideLibraryFunc(static_cast<int>(vec.size()));
}

It doesn't eliminate any of the potential problems with converting size_t to int , but it does tell the compiler that you're doing the conversion on purpose, and it won't warn you about it. 它没有消除将size_t转换为int任何潜在问题,但它确实告诉编译器您是故意进行转换,并且它不会警告您。

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. 为了额外安全检查溢出。

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

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