N3797 :: 9.5 / 2 [class.union]說(shuō):
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
我試圖通過(guò)例子來(lái)理解這個(gè)說(shuō)明:
#include <iostream>#include <limits>struct A{ A(const A&){ std::cout << "~A()" << std::endl; } //A has no default constructor};union U{ A a;};U u; //error: call to implicitly-deleted default constructor of 'U'int main(){}
這種行為對(duì)我來(lái)說(shuō)并不十分清楚. struct A沒(méi)有隱式聲明的默認(rèn)構(gòu)造函數(shù),因?yàn)?2.1 / 4:[class.ctor]說(shuō):
If there is no user-declared constructor for class X, a constructor
having no parameters is implicitly declared as defaulted (8.4).
這意味著struct A沒(méi)有非平凡的默認(rèn)構(gòu)造函數(shù)(根本沒(méi)有默認(rèn)的構(gòu)造函數(shù),特別是非平凡的).這個(gè)聯(lián)合U不必有一個(gè)刪除的默認(rèn)構(gòu)造函數(shù).怎么了?
解決方法:
相關(guān)措辭在C 11 [class.ctor] p5(強(qiáng)調(diào)我的):
A default constructor for a class
X
is a constructor of classX
that can be called without an argument. If there is no user-declared constructor for classX
, a constructor having no parameters is implicitly declared as defaulted (8.4). […] A defaulted default constructor for classX
is defined as deleted if:[…]
X
is a union-like class that has a variant member with a non-trivial default constructor,[…]
- any direct or virtual base class, or non-static data member with no brace-or-equal-initializer, has class type
M
(or array thereof) and eitherM
has no default constructor or overload resolution (13.3) as applied toM
‘s default constructor results in an ambiguity or in a function that is deleted or inaccessible from the defaulted default constructor, or[…]
您的類(lèi)A沒(méi)有默認(rèn)構(gòu)造函數(shù),因此包含類(lèi)型A的非靜態(tài)數(shù)據(jù)成員而沒(méi)有初始化的類(lèi)X(無(wú)論是union還是非union)的默認(rèn)默認(rèn)構(gòu)造函數(shù)(無(wú)論是隱式還是顯式)導(dǎo)致默認(rèn)構(gòu)造函數(shù)為X被刪除.它必須:編譯器根本無(wú)法生成任何其他默認(rèn)構(gòu)造函數(shù).
至于你在評(píng)論中的后續(xù)問(wèn)題:
如果沒(méi)有A沒(méi)有默認(rèn)構(gòu)造函數(shù),它有一個(gè)非平凡的默認(rèn)構(gòu)造函數(shù),那么在union和non-union類(lèi)中使用它有區(qū)別,這也是[class.ctor] p5的一部分:這是我在前面的引文中沒(méi)有強(qiáng)調(diào)的第一個(gè)要點(diǎn).
來(lái)源:https://www.icode9.com/content-4-485801.html聯(lián)系客服