Is this C++ structure initialization trick safe?

前端 未结 16 1179
有刺的猬
有刺的猬 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:28

    What I do is use aggregate initialization, but only specifying initializers for members I care about, e.g:

    STARTUPINFO si = {
        sizeof si,      /*cb*/
        0,              /*lpReserved*/
        0,              /*lpDesktop*/
        "my window"     /*lpTitle*/
    };
    

    The remaining members will be initialized to zeros of the appropriate type (as in Drealmer's post). Here, you are trusting Microsoft not to gratuitously break compatibility by adding new structure members in the middle (a reasonable assumption). This solution strikes me as optimal - one statement, no classes, no memset, no assumptions about the internal representation of floating point zero or null pointers.

    I think the hacks involving inheritance are horrible style. Public inheritance means IS-A to most readers. Note also that you're inheriting from a class which isn't designed to be a base. As there's no virtual destructor, clients who delete a derived class instance through a pointer to base will invoke undefined behaviour.

提交回复
热议问题