Initializing a union with a non-trivial constructor

前端 未结 6 2043
野性不改
野性不改 2020-11-30 00:30

I have a structure which I create a custom constructor to initialize the members to 0\'s. I\'ve seen in older compilers that when in release mode, without doing a memset to

6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-30 00:54

    As mentioned in Greg Rogers' comment to unwesen's post, you can give your union a constructor (and destructor if you wish):

    struct foo
    {
        int a;
        int b;
    };
    
    union bar
    {
        bar() { memset(this, 0, sizeof(*this)); }
    
        int a;
        foo f;
    };
    

提交回复
热议问题