Search code examples
c++constructorinitializationmemset

memset() to initialize object in constructor?


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) {}

Solution

  • 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 PODs 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.