c++11 unrestricted unions example

走远了吗. 提交于 2019-12-05 17:42:42

In the standard, [class.union] mentions in paragraph 2 (in the notes) tells this :

A union can have member functions (including constructors and destructors), but not virtual (10.3) functions. A union shall not have base classes. A union shall not be used as a base class. If a union contains a non-static data member of reference type the program is ill-formed. At most one non-static data member of a union may have a brace-or-equal-initializer. [ 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. — end note ]

Since your class has not-default constructor, the compilation fails.

Paragraph 3 even provides an example :

union U {
int i;
float f;
std::strings;
};

and says :

Since std::string (21.3) declares non-trivial versions of all of the special member functions, U will have an implicitly deleted default constructor, copy/move constructor, copy/move assignment operator, and destructor. To use U, some or all of these member functions must be user-provided.


Bjarne wrote the same thing :

If a union has a member with a user-defined constructor, copy, or destructor then that special function is deleted; that is, it cannot be used for an object of the union type. This is new.

but wrong examples. Both std::string and std::complex have non-default constructors. Therefore, unions with those require union's constructor.

The problem is the presence of m2 in the union. Because complex has a "user-defined" constructor, the constructor for the union that contains it is deleted.

"If a union has a member with a user-defined constructor, a copy operation, a move operation, or a destructor, then that special function is deleted for that union; that is, it cannot be used for an object of the union type.", The C++ Programming Language, p. 215.

union U { int m1;
complex<double> m2; // complex has a constructor
string m3; // string has a constructor (maintaining a serious invariant) 
};

"It is fortunate that U won’t compile." (same reference)

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!