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

后端 未结 5 1700
小蘑菇
小蘑菇 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:07

    In addition to the other notes, sizeof is a compile-time operator, so clear() will not zero out any members added by derived classes (except as noted due to padding weirdness).

    There's nothing really "subtle" about this; memset is a horrible thing to be using in C++. In the rare cases where you really can just fill memory with zeros and expect sane behaviour, and you really need to fill the memory with zeros, and zero-initializing everything via the initializer list the civilized way is somehow unacceptable, use std::fill instead.

提交回复
热议问题