Is this C++ structure initialization trick safe?

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

    I assume the structure is provided to you and cannot be modified. If you can change the structure, then the obvious solution is adding a constructor.

    Don't over engineer your code with C++ wrappers when all you want is a simple macro to initialise your structure.

    #include 
    
    #define MY_STRUCT(x) MY_STRUCT x = {0}
    
    struct MY_STRUCT
    {
        int n1;
        int n2;
    };
    
    int main(int argc, char *argv[])
    {
        MY_STRUCT(s);
    
        printf("n1(%d),n2(%d)\n", s.n1, s.n2);
    
        return 0;
    }
    

提交回复
热议问题