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

后端 未结 5 1699
小蘑菇
小蘑菇 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-29 23:50

    The compiler is likely to add padding bytes to A. So sizeof(A) extends beyond char type (until the end of the padding). However in case of inheritance the compiler might not add the padded bytes. So the call to memset will overwrite part of the subclass.

提交回复
热议问题