Linux kernel: why do 'subclass' structs put base class info at end?

后端 未结 4 1992
走了就别回头了
走了就别回头了 2021-02-04 02:37

I was reading the chapter in Beautiful Code on the Linux kernel and the author discusses how Linux kernel implements inheritance in the C language (amongst other topics). In a

4条回答
  •  名媛妹妹
    2021-02-04 03:21

    The Amiga OS uses this "common header" trick in a lot of places and it looked like a good idea at the time: Subclassing by simply casting the pointer type. But there are drawbacks.

    Pro:

    • You can extend existing data structures
    • You can use the same pointer in all places where the base type is expected, no pointer arithmetic needed, saving precious cycles
    • It feels natural

    Con:

    • Different compilers tend to align data structures differently. If the base structure ended with char a;, then you could have 0, 1 or 3 pad bytes afterwards before the next field of the subclass starts. This led to quite nasty bugs, especially when you had to maintain backwards compatibility (i.e. for some reason, you have to have a certain padding because an ancient compiler version had a bug and now, there is lots of code which expects the buggy padding).
    • You don't notice quickly when you pass the wrong structure around. With the code in your question, fields get trashed very quickly if the pointer arithmetic is wrong. That is a good thing since it raises chances that a bug is discovered more early.
    • It leads to an attitude "my compiler will fix it for me" (which it sometimes won't) and all the casts lead to a "I know better than the compiler" attitude. The latter one would make you automatically insert casts before understanding the error message, which would lead to all kinds of odd problems.

    The Linux kernel is putting the common structure elsewhere; it can be but doesn't have to be at the end.

    Pro:

    • Bugs will show early
    • You will have to do some pointer arithmetic for every structure, so you're used to it
    • You don't need casts

    Con:

    • Not obvious
    • Code is more complex

提交回复
热议问题