C ++: use memset or struct constructor? Which is the fastest?

I find it difficult to understand what is better in C ++:

I use struct to manage clients in the message queue, the structure is as follows:

typedef struct _MsgClient { int handle; int message_class; void *callback; void *private_data; int priority; } MsgClient; 

All of them are objects of POD.

Now I have an array of these structures where I store my clients (I use an array for memory limits, I need to limit fragmentation). So in my class I have something like this:

 class Foo { private: MsgClient _clients[32]; public: Foo() { memset(_clients, 0x0, sizeof(_clients)); } } 

Now I read here and there about SO that using memset is bad in C ++ and that I would rather use a constructor for my structure. I figured out something like this:

 typedef struct _MsgClient { int handle; int message_class; void *callback; void *private_data; int priority; // struct constructor _MsgClient(): handle(0), message_class(0), callback(NULL), private_data(NULL), priority(0) {}; } MsgClient; 

... will eliminate the need for memset . But I'm afraid that when initializing foo, the constructor will be called 32 times, instead of optimizing it as a simple zero from the memory received by the array.

What is your opinion on this?
I just found this: Can a member structure be null-init from the constructor initializer list without calling memset? , is this appropriate in my case (this is different: I have an array, not one instance of the structure)?
Also, according to this post , adding a constructor to my structure will automatically convert it to a structure other than POD, is this correct?

+6
source share
2 answers

In the corresponding implementation, it is great for initializing a value in an array in the constructor initializer list with an empty element initializer. For your array members, this will result in zero initialization of the elements of each array element.

The compiler should be able to make this very efficient, and you do not need to add a constructor to your struct .

eg.

 Foo() : _clients() {} 
+11
source

You can freely memset even in C ++ if you understand what you are doing . About performance - the only way to see which path is really faster is to create your program in the release configuration and then see the generated code in the disassembler.

Using memset sounds a bit faster than initializing each object. However, there is a chance that the compiler will generate the same code.

+3
source

Source: https://habr.com/ru/post/890988/


All Articles