Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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) {}
like image 886
Pietro Avatar asked Mar 02 '15 11:03

Pietro


2 Answers

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.

like image 113
GreenScape Avatar answered Oct 04 '22 03:10

GreenScape


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:

  • Using less code.
  • Being more readable.
  • Removing the need to worry about updating initialisation list when members are added.
  • Removing the need to think about what to do if b needs to default to -1 later.
like image 23
Parker Coates Avatar answered Oct 04 '22 03:10

Parker Coates