In C ++ 11, can you (safely) replace the initialization of memset () with an empty initializer?

I often come across POD structures in code that are manually initialized using memset as follows:

 struct foo; memset(&foo, 0, sizeof(foo)); 

I checked the C ++ 11 standard and it says: "An object whose initializer is an empty set of brackets, i.e. (), must be initialized with a value." Further: "To initialize a [pod struct] value of type T means ... the object is initialized to zero."

So ... this means that you can always safely condense the above code only as follows:

 struct foo{}; 

And have a guaranteed initialized structure, as if you called memset(&foo, 0, ...) ?


If this is the case , then, generally speaking, you can safely initialize something with empty initializers:

 SomeUnknownType foo{}; // will 'foo' be completely "set" to known values? 

I know that this was not always possible in C ++ 03 (until the equivalent initialization syntax ), but is it now possible in C ++ 11 for any type?

+7
c ++ c ++ 11 uniform-initialization
source share
2 answers

You can, of course, initialize any standard layout type using an empty bracket and initialize to zero. Once you add constructors to the drawing, this is not always the case, unfortunately:

 struct foo { int f; }; struct bar { int b; bar() {} }; foo f{}; bar b{}; 

While ff initialized to zero, bb not initialized. However, you cannot do anything about bar , because you cannot memset() it either. It must be fixed.

+8
source share

Memset will initialize it to 0, but an empty bracket will initialize your object (there is a difference).

Quote from the standard:

To initialize an object of type type T means:

  • if T is a class type with a user-declared constructor, then the default constructor for T is called (and initialization is poorly formed if T does not have an available default constructor);

In addition, executing struct foo{}; is safe and it does not take care not to redirect the virtual table pointer.

But do memset(&foo, 0, sizeof(foo)); in the case of virtual functions, it is really very bad, since it resets the pointer to the virtual table.

+3
source share

All Articles