为什么size_type在64位平台上是32位整数?

时间:2017-11-15 10:01:24

标签: c++

std::vector::resize成员函数是这样的:

  

void resize(size_type n);

根据我的理解,size_type应该是64-bit long平台上的64-bit类型。但编译以下程序:

#include <iostream>
#include <climits>
#include <vector>

using namespace std;

vector<char> v;

int main() {
    // your code goes here
    v.resize(INT_MAX +1);
    for (auto i = 0; i < v.size(); i++ ) {
        cout << i << endl;
    }
    return 0;
}

生成以下警告:

g++ -std=c++11 hello.cpp
hello.cpp: In function ‘int main()’:
hello.cpp:11:19: warning: integer overflow in expression [-Woverflow]
  v.resize(INT_MAX +1);

即使我们正在size_type平台上工作,32-bit int仍然是64-bit吗?

1 个答案:

答案 0 :(得分:3)

向量的size_type可能是allocator::size_t的typedef,它(可能)是std::size_t的typedef,是无符号类型。生成的警告与向量的resize()签名无关。您溢出了最大整数限制,INT_MAX + 1表达式调用undefined behaviour。此外,for循环会将i的类型推断为int,在比较有符号和无符号值时也会发出警告。如果您真的想要,可以投射到size_type并添加1

v.resize(static_cast<std::vector<char>::size_type>(INT_MAX) + 1);

并将u文字附加到for循环内的初始值:

for (auto i = 0u; i < v.size(); i++)

您可以使用以下内容获取基础类型名称:

std::cout << typeid(std::vector<char>::size_type).name();