Unions Used as Classes / Structures

I tried to learn more about associations and their usefulness when I was surprised that the following code is absolutely correct and works exactly as expected:

template <class T> union Foo { T a; float b; Foo(const T& value) : a(value) { } Foo(float f) : b(f) { } void bar() { } ~Foo() { } }; int main(int argc, char* argv[]) { Foo<int> foo1(12.0f); Foo<int> foo2((int) 12); foo1.bar(); foo2.bar(); int s = sizeof(foo1); // s = 4, correct return 0; } 

Until now, I had no idea that it is legal to declare unions with templates, constructors, destructors, and even member functions. If relevant, I am using Visual Studio 2012.

When I searched the Internet to find more about using unions in this way, I did not find anything. Is this a new C ++ feature or something special for MSVC? If not, I would like to know more about unions, in particular, examples from them were used as classes (see above). If someone could point me to a more detailed explanation of the unions and their use as data structures, it would be very grateful.

+4
source share
1 answer

Is this a new C ++ feature or something special for MSVC?

No, as BoBtFish said, the standard section 9.5 Unions 1 in the 2003 C ++ standard says:

[...] A union can have member functions (including constructors and destructors) , but not virtual (10.3) functions. The union should not have base classes. A union should not be used as a base class. A class object with a nontrivial constructor (12.1), a nontrivial copy constructor (12.8), a nontrivial destructor (12.4), or a nontrivial copy assignment operator (13.5.3, 12.8) cannot be a member of the union, and there cannot be an array of such objects. If the union contains a static data member or a member of a reference type, the program is poorly formed.

union refers to Section 9 Classes , and the grammar for the class key is as follows:

 class-key: class struct union 

It acts like a class , but has much more limitations. The key limitation is that unions can only have one active non-static element at a time, which is also discussed in paragraph 1 :

In a union, not more than one of the non-static data members can be active at any time , that is, the value of not more than one of the non-static data elements in the union at any time can be saved. [...]

The wording in C++11 draft standard similar, so it has not changed much since 2003 .

Regarding the use of union , in this previous topic there are two common reasons that are covered from different angles. C / C ++: When will someone use the union? Is it basically the balance of C days? To summarize:

This answer to Unions cannot be used as Base class gives a very good idea of ​​why unions implemented as they are in C++ .

+2
source

Source: https://habr.com/ru/post/1495974/


All Articles