container_of宏的定义

6

而不是将 container_of 定义为:

#define container_of(ptr, type, member) ({ \
            const typeof( ((type *)0)->member ) *__mptr = (ptr);
            (type *)( (char *)__mptr - offsetof(type,member) );})

为什么这个简单的方法不能正常工作:
#define container_of(ptr, type, member) ({ \
                    (type *)( (char *)(ptr) - offsetof(type,member) );})

定义中第一行的用途是什么?
1个回答

9

它增加了一定程度的类型安全性。使用第二个版本,您可以将任何内容传递给ptr,并且它将编译成功。使用内核版本,如果您传递与type.member的类型不匹配的指针作为ptr,至少会收到一个警告。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接