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) {}
There is no advantage in using memset()
like this. Leaving behind all the obvious disadvantages and future pain, there is one disadvantage that makes it less efficient than
Message() : a(0), b(0), c(0) {}
This is because POD
s are usually stored in arrays. So good (smart) compiler will have an advantage to replace initialization of multiple objects in an array with a single memset()
, in case of
Message * messages_1 = new Message[100];
Or
std::vector<Message> messages_2;
messages_2.resize(100);
Even when only single object is being constructed, good compiler will use memset()
, behind the curtain.
Note that in C++11 and newer you have a nicer option than either of those:
struct Message
{
unsigned int a = 0;
unsigned int b = 0;
unsigned int c = 0;
};
This should produce identical code (and optimisation opportunities) to the constructor-with-initialisation-list approach while:
b
needs to default to -1
later.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With