Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

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?

like image 258
Chen OT Avatar asked Oct 21 '22 10:10

Chen OT


1 Answers

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.

like image 188
R Sahu Avatar answered Oct 23 '22 10:10

R Sahu