gpt4 book ai didi

c++ - 零长度位域的实际使用

转载 作者:IT老高 更新时间:2023-10-28 21:37:50 26 4
gpt4 key购买 nike

我不太确定 C,但 C++ 允许长度为 0 的未命名位域。例如:

struct X
{
int : 0;
};
  • 问题一:能想到什么实际用途?
  • 问题二:您知道哪些实际用途(如果有)?

编辑冰罪回答后的例子

编辑: 好的,感谢当前的答案,我现在知道了理论目的。但是问题是关于实际用途的,所以它们仍然成立:)

最佳答案

您使用零长度位域作为一种 hacky 方式让您的编译器布局结构以匹配某些外部要求,无论是另一个编译器或架构的布局概念(跨平台数据结构,例如在二进制文件格式)或位级标准的要求(网络数据包或指令操作码)。

一个真实的例子是 NeXT 将 xnu 内核从 Motorola 68000 (m68k) 架构移植到 i386 架构。 NeXT 有一个工作的 m68k 版本的内核。当他们将它移植到 i386 时,他们发现 i386 的对齐要求与 m68k 的不同,以至于 m68k 机器和 i386 机器在 NeXT 供应商特定的 BOOTP 结构的布局上不一致。为了使 i386 结构布局与 m68k 一致,他们添加了一个长度为零的未命名位域,以强制 NV1 结构/nv_U union 为 16 位对齐。

以下是 Mac OS X 10.6.5 xnu 源代码中的相关部分:

/* 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;
};

关于c++ - 零长度位域的实际使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4297095/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com