Why can it be dangerous to use this POD struct as a base class?

后端 未结 5 1698
小蘑菇
小蘑菇 2020-12-29 23:30

I had this conversation with a colleague, and it turned out to be interesting. Say we have the following POD class

struct A { 
  void clear() { memset(this,          


        
5条回答
  •  渐次进展
    2020-12-30 00:06

    The clear method of the base class will only set the values of the class members.

    According to alignment rules, the compiler is allowed to insert padding so that the next data member will occur on the aligned boundary. Thus there will be padding after the type data member. The first data member of the descendant will occupy this slot and be free from the effects of memset, since the sizeof the base class does not include the size of the descendant. Size of parent != size of child (unless child has no data members). See slicing.

    Packing of structures is not a part of the language standard. Hopefully, with a good compiler, the size of a packed structure does not include any extra bytes after the last. Even so, a packed descendant inheriting from a packed parent should produce the same result: parent sets only the data members in the parent.

提交回复
热议问题