Is this C++ structure initialization trick safe?

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

    If MY_STRUCT is your code, and you are happy using a C++ compiler, you can put the constructor there without wrapping in a class:

    struct MY_STRUCT
    {
      int n1;
      int n2;
      MY_STRUCT(): n1(0), n2(0) {}
    };
    

    I'm not sure about efficiency, but I hate doing tricks when you haven't proved efficiency is needed.

提交回复
热议问题