std::size_t 是什么



std::size_t 是什么

在UNIX中,有很多的地方使用size_t代替int,请问他们有什么区别? 
另外,size_t在那个头文件中声明的?应该是使用typedef吧? 
看到一句话“size_t is the unsigned integer type returned by the sizeof operator”,大家帮忙理解一下,为什么和sizeof有关 
使用size_t是因为这个类型是与平台无关。为什么无关,就是因为他是sizeof的返回直。当你移植你的代码的时候,那不因为平台的不同而不同。大概是在stddef.h里的 
2 楼size_t(阿跑) 回复于 2002-07-03 17:06:07 得分 5 
size_t 在 stddef.h里定义。 
在不同的实现里可能不一定相同, 
In Borland implementation of the ANSI C standard, the type size_t is unsigned. 
也就是typedef unsigned int size_t; 
size_t is the unsigned integer type returned by the sizeof operator 
的意思应该是说sizeof(size_t) == sizeof(unsigned int) 
3 楼xkak2(矗立云端) 回复于 2002-07-03 17:42:00 得分 15 
c中的int long等等的长度是随平台的而变化的,为了保证移植性,所以用一个中间类型size_t代表所有长度的类型,sizeof运算符返回的就是这个类型的数 据。在移植时,可以用typedef来指定该平台上size_t的真实数据类型。比如在win32和unix平台上,就是typedef unsinged int size_t。 
4 楼sokoban() 回复于 2002-07-03 19:11:46 得分 0 
typedef unsigned int size_t; 
unsinged int,unsigned long,size_t还是std::size_t? 
首先四种类型都是无符号类型,是用以表示元素个数或者数组索引的最佳类型。在作为函数参数时,不需像有符号类型那样检测值是否小于零。 
1. ::size_t还是std::size_t 
请使用std::size_t,因为你处于C++的世界。 
在此,所有C++标准库组件用以表示元素个数的类型 (比如size()或者operator[])都是std::size_t。 
std::size_t count = array.size(); // array是typedef vector 
std::size_t index = 0; 
array[ index ] = 0; 
注意: 
1. 如果某个CPP没有使用任何C++标准库组件,那么就有可能需要包含 头文件。 
2. std::size_t其实就是::size_t (::size_t被引入到namespace std中(你可以在中找到) 
基本上我们不会考虑unsigned int和unsigned long,因为处在C++的世界,使用C++标准库组件就是在所难免了。 
如果你非要了解其细枝末节的话,那么下面是一份清单: 
unsigned int 和 unsigned long比较(不考虑32位以下的平台) 
如果不考虑可移植性: 
在32位平台上更应该使用unsigned int,因为它: 
1. 和unsigned long 一样的大小,32位可以表示到42.9亿。 
2. 比unsigned long更常用 
3. 和std::size_t是一样的类型 
如果是64位平台的话: 
1. unsinged int仍是32位,而unsigned long就是64位了。 
2. 更应该使用unsigned long因为处理器对64位具有更快的处理速度。 
就目前而言,64位平台还不够成熟,所以向64位平台的移植基本不做考虑。 
但是如果你坚持要考虑可移植性(注意是硬件32位平台向64位移植,而非软件): 
1. 如果对速度敏感:使用unsigned long,无论在32位还是64位都有最快的处理速度。 
2. 如果对内存敏感:使用unsigned int,使用内存量不会因平台而改变。 
不过通常对于硬件平台的可移植性的考虑都是多余的(不够敏捷哦)。 
总结: 
请在任何情况下使用std::size_[size=medium][/size]
来自:http://lemoncyb.iteye.com/blog/1614848
http://blog.sina.com.cn/s/blog_89cb90270101k4ql.html