Reputation: 31
I have many POD struct with a lot of member variables. Instead of initializing each members in the constructor, I simply use memset. Is this valid in C++?
struct foo
{
foo() { std::memset(this, 0, sizeof (foo)); }
int var1;
float var2;
double var3;
// more variables..
};
Upvotes: 3
Views: 1707
Reputation: 279325
It's not guaranteed to work, since the C++ standard permits implementations in which all-bits-zero is a trap representation of float
or double
. So reading those members on such an implementation would have undefined behavior.
The same applies to any padding bytes that the implementation might put between the data members -- modifying them is either undefined behavior or else puts the object into an undefined state, that has undefined behavior when used. I forget which.
In practice it will work on all implementations I know, though.
Other answers make valid points about your class being non-POD (C++03) and non-trivial (C++11). Thing is, even if you removed the constructor and called memset
from somewhere else it would still not be guaranteed to work by the standard. But if you did remove the constructor you could use aggregate initialization:
foo f = {0};
and that would intialize all members to zero values (whether or not that is represented by all-bits-zero), guaranteed.
Upvotes: 3
Reputation: 4463
According to standard your struct is not POD type and thus it is not allowed to use memset.
A trivial class is a class that has a default constructor (12.1), has no non-trivial default constructors , and is trivially copyable
10 A POD struct108 is a non-union class that is both a trivial class and a standard-layout class, and has no non-static data members of type non-POD struct, non-POD union (or array of such types).
Since your class have non-trivial default constructor it is no longer trivial, and as result not a POD type.
Most likely is will be working on most of the compilers, no guarantee thru.
Upvotes: 2