If a union contains a non-static data member with a non-trivial special member function (default constructor,copy/move constructor,copy/move assignment,or destructor),that function is deleted by default in the union and needs to be defined explicitly by the programmer.
At most one data member can have a default member initializer.
我正在尝试以下代码:
struct X { ~X() {}; }; union U { X x; ~U() {}; }; int main() { U s1{}; // works,probably aggregate initialization U s2; // DOES NOT compile,why? }
这里X(用作联合的数据成员)具有用户提供的析构函数,因此,联合的析构函数默认删除.所以我明确提供一个.但是,代码无法编译,带有错误
note: ‘U::U()’ is implicitly deleted because the default definition would be ill-formed:
如果我删除最后一行U s2 ;.
问题这里发生了什么?为什么U s1 {};编译,但U s2;才不是?是否将联盟的默认ctor标记为已删除(如果是这样,为什么?!),而在第一种情况下,我们只是聚合初始化?请注意,如果我提供U(){}; // not U()= default;代码编译(但不是如果我只提供一个X的ctor).
编辑
挖掘标准(N4527)后:
工会:9.5 / 2 [class.union]
[Note: If any non-static data member of a union has a non-trivial default constructor (12.1),copy constructor (12.8),move constructor (12.8),copy assignment operator (12.8),move assignment operator (12.8),or destructor (12.4),the corresponding member function of the union must be user-provided or it will be implicitly deleted (8.4.3) for the union. —endnote]
似乎这是一个gcc错误(现在报道here).代码编译在clang和gcc 4.8.2或更早版本,它在gcc4.9和更高版本(感谢@ T.C.指出)中断.
编译器:g 5.3,-std = c 11已使用.