Initializing a union with a non-trivial constructor

前端 未结 6 2042
野性不改
野性不改 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:56

    AFAIK union members may not have constructors or destructors.

    Question 1: no, there's no such guarantee. Any POD-member not in the constructor's initialization list gets default-initialized, but that's with a constructor you define, and has an initializer list. If you don't define a constructor, or you define a constructor without an initializer list and empty body, POD-members will not be initialized.

    Non-POD members will always be constructed via their default constructor, which if synthesized, again would not initialize POD-members. Given that union members may not have constructors, you'd pretty much be guaranteed that POD-members of structs in a union will not be initialized.

    Question 2: you can always initialize structures/unions like so:

    struct foo
    {
        int a;
        int b;
    };
    
    union bar
    {
        int a;
        foo f;
    };
    
    bar b = { 0 };
    

提交回复
热议问题