Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memset POD struct with this pointer

Tags:

c++

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..
};
like image 407
grasshopper Avatar asked Dec 18 '25 04:12

grasshopper


2 Answers

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.

like image 197
Steve Jessop Avatar answered Dec 19 '25 18:12

Steve Jessop


According to standard your struct is not POD type and thus it is not allowed to use memset.

9 Classes

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.

like image 26
alexrider Avatar answered Dec 19 '25 16:12

alexrider



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!