Why do unions have a deleted default constructor if just one of its members doesn't have one?

后端 未结 2 1490
南笙
南笙 2020-12-09 10:47

N3797::9.5/2 [class.union] says:

If any non-static data member of a union has a non-trivial default constructor (12.1), copy c

2条回答
  •  南方客
    南方客 (楼主)
    2020-12-09 11:32

    In your example, the problem is not that your code has no non trivial defautl constructor, but that it has a copy constructor.

    But generally, a union has several members: "at most one of the non-static data members can be active at any time, that is, the value of at most one of the non-static data members can be stored in a union at any time" (9.5/1).

    Suppose you have a union with several members some of them having non trivial constructors or copy constructors:

    union W {
        A a; 
        int i; 
    };
    

    When you would create an object:

    W w;  
    

    how should this object be default constructed ? Which member should be the active one ? How should such an object be default-copied ? Is it the A or the int that should be constructed/copied ?

    This is why the standard foresses that your union has a deleted default constructor (copy constructor in your case). It should be sufficient to user-provide the missing default function.

    union W
    {
        int i;
        A a;
        W() { /*...*/ }
        W(const W&c) { /*...*/ }
    };
    

    This paper explains the rationale and the wording of C++11 on the topic in its full details.

    Important remark: Unfortunately, unrestricted unions are not supported by MSVC13 : it still does not accept ANY member having ANY of the non-trivial default function user defined. GCC accepts it since 4.6 and clang since 3.1.

提交回复
热议问题