Initializing a union with a non-trivial constructor

前端 未结 6 2057
野性不改
野性不改 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 01:09

    Can you do something like this?

    class Outer
    {
    public:
        Outer()
        {
            memset(&inner_, 0, sizeof(inner_));
        }
    private:
        union Inner
        {
            int qty_;
            double price_;
        } inner_;
    };
    

    ...or maybe something like this?

    union MyUnion
    {
        int qty_;
        double price_;
    };
    
    void someFunction()
    {
        MyUnion u = {0};
    }
    

提交回复
热议问题