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

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

概述我正在努力了解C11如何扩展工会.改变的一件事是现在使用非平凡特殊成员函数的非静态数据成员的能力.从 cppreference.com If a union contains a non-static data member with a non-trivial special member function (default constructor, copy/move constructor, 我正在努力了解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默认的构造函数被删除.

总结

以上是内存溢出为你收集整理的C 11中的工会:默认构造函数似乎被删除全部内容,希望文章能够帮你解决C 11中的工会:默认构造函数似乎被删除所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://www.outofmemory.cn/langs/1252067.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-07
下一篇 2022-06-07

发表评论

登录后才能评论

评论列表(0条)

保存