微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

C 11中的工会:默认构造函数似乎被删除

我正在努力了解C11如何扩展工会.改变的一件事是现在使用非平凡特殊成员函数的非静态数据成员的能力.从 cppreference.com

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?
}

Live on Coliru

这里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已使用.

解决方法

cpp引用引用不清楚.会发生什么事情,如果工会的任何一个记忆员都定义了任何这些非平凡的特殊成员函数,那么所有这些都将在联合中删除.

所以,因为你有一个非平凡的析构函数X,U认的构造函数删除.

原文地址:https://www.jb51.cc/c/112835.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐