[英]Why is size_type a 32-bit integer on a 64-bit platform?
The std::vector::resize member function is like this: std :: vector :: resize成员函数如下所示:
void resize (size_type n); void resize(size_type n);
Per my understanding, size_type
should be a 64-bit long
type on a 64-bit
platform. 据我了解, size_type
在64-bit
平台上应为64-bit long
类型。 But compiling the following program: 但是编译以下程序:
#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;
}
The following warning is generated: 生成以下警告:
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);
So the size_type
is still 32-bit int
even though we're working on a 64-bit
platform? 因此,即使我们在64-bit
平台上工作, size_type
仍然是32-bit int
?
The vector's size_type
is probably a typedef for allocator::size_t
which is (probably) a typedef for std::size_t which is an unsigned type. 向量的size_type
可能是allocator::size_t
的typedef,(可能)是std :: size_t的typedef,这是一个无符号类型。 The generated warning has nothing to do with the vector's resize()
signature. 生成的警告与向量的resize()
签名无关。 You are overflowing the max integer limit and your INT_MAX + 1
expression invokes undefined behaviour . 您正在溢出最大整数限制,并且INT_MAX + 1
表达式调用未定义的行为 。 Also the for
loop deduces the type of i
to be int
which will also issue a warning when comparing signed and unsigned values. 同样, for
循环推导i
的类型为int
,当比较有符号和无符号值时也将发出警告。 If you really want to you can cast to size_type
and add 1
: 如果确实需要,可以将其转换为size_type
并添加1
:
v.resize(static_cast<std::vector<char>::size_type>(INT_MAX) + 1);
and append the u
literal to initial value inside the for
loop: 并将u
文字附加到for
循环内的初始值:
for (auto i = 0u; i < v.size(); i++)
You can get the underlying type name with: 您可以使用以下方法获取基础类型名称:
std::cout << typeid(std::vector<char>::size_type).name();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.