Is this C++ structure initialization trick safe?

前端 未结 16 1159
有刺的猬
有刺的猬 2020-12-23 17:56

Instead of having to remember to initialize a simple \'C\' structure, I might derive from it and zero it in the constructor like this:

struct MY_STRUCT
{
            


        
16条回答
  •  春和景丽
    2020-12-23 18:32

    From an ISO C++ viewpoint, there are two issues:

    (1) Is the object a POD? The acronym stands for Plain Old Data, and the standard enumerates what you can't have in a POD (Wikipedia has a good summary). If it's not a POD, you can't memset it.

    (2) Are there members for which all-bits-zero is invalid ? On Windows and Unix, the NULL pointer is all bits zero; it need not be. Floating point 0 has all bits zero in IEEE754, which is quite common, and on x86.

    Frank Kruegers tip addresses your concerns by restricting the memset to the POD base of the non-POD class.

提交回复
热议问题