C11 添加了“匿名结构和联合”等内容。
我四处寻找,但找不到关于匿名结构和联合何时有用的明确解释。我问是因为我不完全理解它们是什么。我知道它们是后来没有名称的结构或联合,但我一直(不得不?)将其视为错误,因此我只能设想用于命名结构。
结构内部的匿名联合在实践中非常有用。考虑到您想要实现一个有区别的总和类型(或标记的 union),一个带有布尔值和浮点数或 a char*
(即字符串)的聚合,具体取决于布尔标志。使用 C11,您应该能够编码
typedef struct {
bool is_float;
union {
float f;
char* s;
};
} mychoice_t;
double as_float(mychoice_t* ch)
{
if (ch->is_float) return ch->f;
else return atof(ch->s);
}
使用 C99,您必须命名联合和代码ch->u.f
,ch->u.s
这样可读性较差且更冗长。
匿名结构和联合的典型和现实世界使用是为数据提供替代视图。例如在实现 3D 点类型时:
typedef struct {
union{
struct{
double x;
double y;
double z;
};
double raw[3];
};
}vec3d_t;
vec3d_t v;
v.x = 4.0;
v.raw[1] = 3.0; // Equivalent to v.y = 3.0
v.z = 2.0;
如果您与需要 3D 向量作为指向三个双精度数的指针的代码接口,这很有用。与其做f(&v.x)
丑陋的事,不如做f(v.raw)
让你的意图明确的事。
struct bla {
struct { int a; int b; };
int c;
};
该类型struct bla
具有 C11 匿名结构类型的成员。
struct { int a; int b; }
没有标签且对象没有名称:它是一种匿名结构类型。
您可以通过以下方式访问匿名结构的成员:
struct bla myobject;
myobject.a = 1; // a is a member of the anonymous structure inside struct bla
myobject.b = 2; // same for b
myobject.c = 3; // c is a member of the structure struct bla
另一个有用的实现是当您处理 rgba 颜色时,因为您可能希望单独访问每种颜色或作为单个 int 访问。
typedef struct {
union{
struct {uint8_t a, b, g, r;};
uint32_t val;
};
}Color;
现在您可以访问单个 rgba 值或整个值,其最高字节为 rie:
int main(void)
{
Color x;
x.r = 0x11;
x.g = 0xAA;
x.b = 0xCC;
x.a = 0xFF;
printf("%X\n", x.val);
return 0;
}
打印 11AACCFF
我不确定为什么 C11 允许在结构中使用匿名结构。但是 Linux 将它与某种语言扩展一起使用:
/**
* struct blk_mq_ctx - State for a software queue facing the submitting CPUs
*/
struct blk_mq_ctx {
struct {
spinlock_t lock;
struct list_head rq_lists[HCTX_MAX_TYPES];
} ____cacheline_aligned_in_smp;
/* ... other fields without explicit alignment annotations ... */
} ____cacheline_aligned_in_smp;
我不确定该示例是否绝对必要,除非要明确意图。
编辑:我发现了另一种更清晰的类似模式。匿名结构功能与此属性一起使用:
#if defined(RANDSTRUCT_PLUGIN) && !defined(__CHECKER__)
#define __randomize_layout __attribute__((randomize_layout))
#define __no_randomize_layout __attribute__((no_randomize_layout))
/* This anon struct can add padding, so only enable it under randstruct. */
#define randomized_struct_fields_start struct {
#define randomized_struct_fields_end } __randomize_layout;
#endif
即用于随机化字段顺序的语言扩展/编译器插件(ASLR 风格的利用“强化”):
struct kiocb {
struct file *ki_filp;
/* The 'ki_filp' pointer is shared in a union for aio */
randomized_struct_fields_start
loff_t ki_pos;
void (*ki_complete)(struct kiocb *iocb, long ret, long ret2);
void *private;
int ki_flags;
u16 ki_hint;
u16 ki_ioprio; /* See linux/ioprio.h */
unsigned int ki_cookie; /* for ->iopoll */
randomized_struct_fields_end
};
好吧,如果您在代码中只从该结构声明一次变量,为什么它需要一个名称?
struct {
int a;
struct {
int b;
int c;
} d;
} e,f;
您现在可以编写诸如e.a
,之类的东西f.d.b
。
(我添加了内部结构,因为我认为这是匿名结构的最多用法之一)