Is memset safe to have a simple structure with a custom default constructor?

I know that if the C ++ structure is Plain Old Data ("POD"), this ensures that there is no magic in its memory structure, so this means that it is safe memcpyfor the byte array and memcpyback.

I also know that in the standard, the POD structure should not have a user-defined constructor. In the project that I have now, there are some simple structures (with data fields only) with a default constructor that initializes data members to 0. I saw what other clients used memset(&obj, 0, sizeof obj);before using the structure.

Is it safe or safe for memseta non-POD structure before using it?

+4
source share
2 answers

Having a constructor does not make structnon-POD.

An aggregate class is called a POD if it does not have a custom copy assignment operator and destructor, and none of its non-static members is a POD class class, non-POD array, or reference.

Given that it’s completely safe to call

memset(&obj, 0, sizeof obj);

for an object structthat has a constructor if it is a POD.

Regardless of whether it is in order or not, it depends. If the default constructor structwants the member to be initialized to 1for normal behavior, the above call memsetmay affect the behavior of the code, which depends on 1, which is the default value.

Take an example of the following struct:

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

Direction , . , . memset 0, , , .

, POD ++ 03 ++ 11.

memset(&obj, 0, sizeof obj); .

+2

. memset, i.e

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

const , memset . memset PODS. 2 .

0

Source: https://habr.com/ru/post/1536889/


All Articles