简体   繁体   中英

C++: Use memset or a struct constructor? What's the fastest?

I'm having trouble figuring out which is better in C++:

I use a struct to manage clients in a message queue, the struct looks like this:

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

All of these being POD entities.

Now, I have an array of these structs where I store my clients (I use an array for memory constraints, I have 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 on SO that using memset is bad in C++, and that I'd rather use a constructor for my structure. I figured 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;

...would eliminate the need of the memset . But my fear is that when foo is initialized, the struct constructor will be called 32 times, instead of optimizing it as a simple zero out of the memory taken by the array.

What's your opinion on this?
I just found this: Can a member struct be zero-init from the constructor initializer list without calling memset? , is it appropriate in my case (which is different: I have an array, not a single instance of the structure)?
Also, according to this post , adding a constructor to my structure will automatically convert it into a non-POD structure, is it right?

On a conforming implementation, it's perfectly valid to value-initialize an array in the constructor initializer list with an empty member initializer. For your array members, this will have the effect of zero-initializing the members of each array element.

The compiler should be able to make this very efficient and there's no need for you to add a constructor to your struct .

Eg

Foo() : _clients() {}

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

Using memset sounds somewhat faster than per-object initialization. However there's a chance the compiler will generated the same code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM