There is technically no object property in C++ which specifies that user code can legally memset
a C++ object. And that includes POD, so if you want to be technical, your code was never correct. Even TriviallyCopyable is a property about doing byte-wise copies between existing objects (sometimes through an intermediary byte buffer); it says nothing about inventing data and shoving it into the object's bits.
That being said, you can be reasonably sure this will work if you test is_trivially_copyable
and is_trivially_default_constructible
. That last one is important, because some TriviallyCopyable types still want to be able to control their contents. For example, such a type could have a private int
variable that is always 5, initialized in its default constructor. So long as no code with access to the variable changes it, it will always be 5. The C++ object model guarantees this.
So you can't memset
such an object and still get well-defined behavior from the object model.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…