加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 06:03:47 所属栏目:百科 来源:网络整理
导读:我正在努力了解C11如何扩展工会.改变的一件事是现在使用非平凡特殊成员函数的非静态数据成员的能力.从 cppreference.com If a union contains a non-static data member with a non-trivial special member function (default constructor,copy/move constru
我正在努力了解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默认的构造函数被删除.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读