您的位置:首页 > 其它

C++库研究笔记——几个注意(size_t)

2013-07-29 09:32 232 查看
总之,用size_t 保证可移植性,保证其可以表示出最大需要表示的长度。

size_t 在stddef.h 中无命名空间

在<cstddef>有std::

size_t 与ptrdiff_t 要联合使用

When
i
is
signed and
size
is
unsigned, then
i
is
converted to unsigned before the comparison is performed. This is part of what are called the usual arithmetic conversions.http://stackoverflow.com/questions/4311538/strange-behaviour-with-for-loop-and-size-t


unsigned int vs.
size_t:


When to use std::size_t?


Difference
between size_t and std::size_t


About size_t and ptrdiff_t

(ptrdiff_t 在64位下有更高的效率)

#include <iostream>
#include <stddef.h>

template <typename T, int N>
int size(T (&)
)
{
    return N;
}

int main()
{
    int a[20];
    std::cout<<size(a)<<std::endl;

    std::cout<<"sizeof(short):"<<sizeof(short)<<std::endl;
    std::cout<<"sizeof(float):"<<sizeof(float)<<std::endl;
    std::cout<<"sizeof(double):"<<sizeof(double)<<std::endl;
    std::cout<<"sizeof(long):"<<sizeof(long)<<std::endl;
    std::cout<<"sizeof(size_t):"<<sizeof(size_t)<<std::endl;

    std::cout<<"sizeof(ptrdiff_t):"<<sizeof(ptrdiff_t)<<std::endl;  // error when not using #include <stddef.h>
    std::cout<<"sizeof(ptrdiff_t):"<<sizeof(std::ptrdiff_t)<<std::endl;
    return 0;
}


结果:

20

sizeof(short):2

sizeof(float):4

sizeof(double):8

sizeof(long):8

sizeof(size_t):8

sizeof(ptrdiff_t):8

sizeof(ptrdiff_t):8
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: