您的位置:首页 > 编程语言 > C语言/C++

【c/c++】size_t和size_type的差别

2016-01-12 15:05 417 查看
size_type

由string类类型和vector类类型定义的类型,用以保存任意string对象或vector对象的长度,标准库类型将size_type定义为unsigned类型

string抽象意义是字符串, size()的抽象意义是字符串的尺寸, string::size_type抽象意义是尺寸单位类型

string::size_type它在不同的机器上,长度是可以不同的,并非固定的长度。但只要你使用了这个类型,就使得你的程序适合这个机器。与实际机器匹配。

size_t

size_t是为了方便系统之间的移植而定义的。(它就是一个无符号整型,有木有!!!)

在32位系统上定义为 unsigned int

在64位系统上定义为 unsigned long

更准确的说法是在32位系统上是32位无符号整型

在64位系统上是64位无符号整型

size_t一般用来表示一种计数,比如有多少东西被拷贝等。

sizeof操作符的结果类型是size_t,

该类型保证能容纳实现所建立的最大对象的字节大小。

它的意义大致是"适于计量内存中可容纳的数据项目的个数的无符号整数类型"。

所以,它在数组下标和内存管理函数之类的地方广泛使用

为了使自己的程序有很好的移植性,c++程序员应该尽量使用size_t和size_type而不是int, unsigned

stackover解释:

The standard containers define size_type as a typedef to Allocator::size_type (Allocator is a template parameter), which for std::allocator
is defined to be size_t.

So for the standard case, they are the same.

However, if you use a custom allocator a different underlying type could be used.

So container::size_type is preferable for maximum portability.(可移植性)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: