Monday, September 26, 2011

memset in constructors

Once in a while we write memset in constructors to avoid typing out the long initializer list.

Typical example code is:

memset(this, 0, sizeof (*this));

This can lead to different behaviors based on whether the class/struct on which this is being done is a POD or a non-POD. POD stands for plain old data types. A POD is essentially a collection of fields.It doesn’t have any specific semantics of its own.

  • If the class is non-POD, memset() will cause undefined behavior.
  • If the class is polymorphic then, Usually the virtual table pointer also becomes 0, leading to problems.
  • Even with POD, there is no guarantee that memset-ting things with 0 actually sets the variables to 0 -- this is especially the case if the types are float or double. The representation of 0.0 in float/double may not be all bits equal to 0. IEEE 754 does guarantee that all bits zero is equal to 0.0 but C++ doesn’t require IEEE 754 for representing floating point numbers and other representations may not guarantee the same.

Reference

http://www.codeguru.com/forum/archive/index.php/t-430848.html