零长度位字段的实际使用 [英] Practical Use of Zero-Length Bitfields
问题描述
我不能完全肯定C,但C ++允许长度为0的无名位字段。例如:
I am not totally sure about C, but C++ allows unnamed bit-fields of 0 length. For example:
struct X
{
int : 0;
};
- 问题一:可以的您的想怎么看的实际用途
- 问题二:什么现实世界的实际用途(如果有的话),你知道
- Question one: What practical uses of this can you think of?
- Question two: What real-world practical uses (if any) are you aware of?
编辑的冰犯罪的回答后,例如
Edited the example after ice-crime's answer
的 修改的确定,这要归功于目前的答案,我现在知道了理论上的目的。但问题是关于实际用途,使他们仍然坚持:)
OK, thanks to the current answers I now know the theoretical purpose. But the questions are about practical uses so they still hold :)
推荐答案
您使用零长度位字段作为一个哈克方式得到你的编译器打下了一个结构来匹配一些外部的要求,无论是另一种编译器或体系结构的概念布局(跨平台数据结构,诸如在一个二进制文件格式)或位级标准的要求(网络分组或指令运算codeS)。
You use a zero-length bitfield as a hacky way to get your compiler to lay out a structure to match some external requirement, be it another compiler's or architecture's notion of the layout (cross-platform data structures, such as in a binary file format) or a bit-level standard's requirements (network packets or instruction opcodes).
一个真实世界的例子是,当NeXT的移植从摩托罗拉68000(m68k的)架构的XNU内核i386架构。 NeXT公司有自己的内核工作m68k的版本。当他们把它移植到i386的,他们发现,在i386的对齐要求从m68k的在这样一种方式,一个m68k的机器和一台i386机器没有在接下来的供应商特定BOOTP结构布局同意不同。为了使i386的结构布局与m68k的同意,他们增加了长度为零强制的未命名位域 NV1
结构/ nv_U
工会为16位对齐。
A real-world example is when NeXT ported the xnu kernel from the Motorola 68000 (m68k) architecture to the i386 architecture. NeXT had a working m68k version of their kernel. When they ported it to i386, they found that the i386's alignment requirements differed from the m68k's in such a way that an m68k machine and an i386 machine did not agree on the layout of the NeXT vendor-specific BOOTP structure. In order to make the i386 structure layout agree with the m68k, they added an unnamed bitfield of length zero to force the NV1
structure/nv_U
union to be 16-bit aligned.
下面是从Mac OS X 10.6.5 XNU源$ C $ c中的相关部分:
Here are the relevant parts from the Mac OS X 10.6.5 xnu source code:
/* from xnu/bsd/netinet/bootp.h */
/*
* Bootstrap Protocol (BOOTP). RFC 951.
*/
/*
* HISTORY
*
* 14 May 1992 ? at NeXT
* Added correct padding to struct nextvend. This is
* needed for the i386 due to alignment differences wrt
* the m68k. Also adjusted the size of the array fields
* because the NeXT vendor area was overflowing the bootp
* packet.
*/
/* . . . */
struct nextvend {
u_char nv_magic[4]; /* Magic number for vendor specificity */
u_char nv_version; /* NeXT protocol version */
/*
* Round the beginning
* of the union to a 16
* bit boundary due to
* struct/union alignment
* on the m68k.
*/
unsigned short :0;
union {
u_char NV0[58];
struct {
u_char NV1_opcode; /* opcode - Version 1 */
u_char NV1_xid; /* transcation id */
u_char NV1_text[NVMAXTEXT]; /* text */
u_char NV1_null; /* null terminator */
} NV1;
} nv_U;
};
这篇关于零长度位字段的实际使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!