我正在寻找关于基本c++类型大小的详细信息。
我知道这取决于架构(16位、32位、64位)和编译器。
但是c++有标准吗?
我在32位架构上使用Visual Studio 2008。以下是我得到的答案:
char : 1 byte
short : 2 bytes
int : 4 bytes
long : 4 bytes
float : 4 bytes
double: 8 bytes
我试图在不同的架构和编译器下找到char、short、int、long、double、float(以及其他我没有想到的类型)的大小的可靠信息,但没有多大成功。
实际上没有这样的事情。通常,std::size_t表示当前体系结构上的无符号本机整数大小。即16位、32位或64位,但并不总是如此,就像这个答案的评论中指出的那样。
至于所有其他内置类型,它实际上取决于编译器。以下是摘自最新c++标准的当前工作草案的两段摘录:
There are five standard signed integer types : signed char, short int, int, long int, and long long int. In this list, each type provides at least as much storage as those preceding it in the list.
For each of the standard signed integer types, there exists a corresponding (but different) standard unsigned integer type: unsigned char, unsigned short int, unsigned int, unsigned long int, and unsigned long long int, each of which occupies the same amount of storage and has the same alignment requirements.
如果您愿意,您可以静态(编译时)断言这些基本类型的sizeof。如果假设的大小发生变化,它会提醒人们考虑移植您的代码。
c++标准是这样说的:
3.9.1,§2:
There are five signed integer types :
"signed char", "short int", "int",
"long int", and "long long int". In
this list, each type provides at least
as much storage as those preceding it
in the list. Plain ints have the
natural size suggested by the
architecture of the execution
environment (44); the other signed
integer types are provided to meet
special needs.
(44) that is, large enough to contain
any value in the range of INT_MIN and
INT_MAX, as defined in the header
<climits>.
结论:这取决于您使用的是哪种体系结构。其他任何假设都是错误的。