Chen OT
Chen OT

Reputation: 3614

Is it safe to memset the plain struct with user-defined default constructor?

I know that if a C++ struct is Plain Old Data ("POD") then this guarantees there is no magic in its memory structure, so it means a memcpy to an array of bytes and memcpy back is safe.

I also know that in the standard a POD struct should not have user-defined constructor. In the project I own now, there are some plain structs (with only data fields) with a default constructor defined which initializies the data members to 0. I saw other clients would use memset(&obj, 0, sizeof obj); before using the struct.

Is it ok or safe to memset the non-POD struct before I use it?

Upvotes: 5

Views: 1792

Answers (2)

R Sahu
R Sahu

Reputation: 206697

Having a constructor does not make a struct non-POD.

An aggregate class is called a POD if it has no user-defined copy-assignment operator and destructor and none of its nonstatic members is a non-POD class, array of non-POD, or a reference.

Given that, it is perfectly safe to call

memset(&obj, 0, sizeof obj);

on an object of a struct that has a constructor as long as it is a POD.

Whether it is OK or not, depends. If the default constructor of the struct wants a member to be initialized to 1 for sane behavior, the above call to memset may impact the behavior of code that depends on 1 being the default value.

Take the example of the following struct:

struct Direction
{
   Direction() : x(1.0), y(0.0), z(0.0) {}
   double x;
   double y;
   double z;
};

An object of type Direction expects that at least of one of the components will be non-zero. You can't define a direction when all the components are zero. If you use memset to set everything to 0, code will likely break.

EDIT It appears, from the comments below, as though the definition of a POD has changed from C++03 to C++11.

Using memset(&obj, 0, sizeof obj); may not be safe after all.

Upvotes: 3

user3543576
user3543576

Reputation: 54

IMO this depends on the use case. I have seen memset used to set the data with white space character on few mainframe appications i.e

memset(&obj, ' ', sizeof(obj));

In case the struct defines a const variable and initializes the value, memset would override such value. So it depends and most cases safe to use memset to initialize for PODS. thats my 2 cents.

Upvotes: 0

Related Questions