I found this piece of C++ code that uses memset() to initialize an object:
struct Message
{
Message()
{
memset(this, 0, sizeof(Message));
}
unsigned int a, b, c;
};
Since this is a POD structure, this code should be fine.
Is there any advantage in using memset instead of a constructor such as:
Message() : a(0), b(0), c(0) {}
memsetthem or something like this in second case. But if will decide later to build a hierarchy, you done goofed.static_assertright before/after the memset. This tells both the human reader as well as the compiler that you assume Message to be a POD; the compiler will fail if it isn't, and the reader will know why you think memset would be ok.memsetshould enforce a call to memory, which won't be optimized out, as it will be considered having side effects. Declaring initial values statically gives more options for compiler to optimize.static_assert(std::is_standard_layout<Message::value, "class is not memsettable")Message x = Message();, however, this doesn't preventMessage x;to be written, in which case it is uninitialized. But that's simply how PODs work...