我了解到C++11中提出了非限制性联合体(unrestricted unions)
作为其功能之一。请问有人能够解释其语义以及其提供的优势吗?
维基百科上有解释:http://en.wikipedia.org/wiki/C%2B%2B0x#Unrestricted_unions
在询问关于C++0x特性的解释之前,请先在那里搜索。
无限制联合体
在标准C++中,对于可以成为联合体成员的对象类型存在限制。例如,联合体不能包含定义了非平凡构造函数的任何对象。C++0x将减轻其中一些限制,允许联合体用于更多之前不被允许使用的类型[6]。以下是一个在C++0x中允许的简单联合体示例:
//for placement new #include <new> struct Point { Point() {} Point(int x, int y): x_(x), y_(y) {} int x_, y_; }; union U { int z; double w; Point p; // Illegal in C++; point has a non-trivial constructor. // However, this is legal in C++0x. U() { new( &p ) Point(); } // No nontrivial member functions are //implicitly defined for a union; // if required they are instead deleted // to force a manual definition. };
这些更改不会破坏任何现有的代码,因为它们仅仅放宽了当前的规则。