Use of union in C/C ++. Detailed description. Example

Source: Internet
Author: User

Union is not much seen in C/C ++. However, in some areas where memory requirements are particularly strict, union is frequently used, so what exactly is Union, how to use it, and what should we pay attention? I have tried some simple answers to these questions. There must be some improper answers!


1. What is union?
"Union" is a special class and a data structure of the construction type. Different data types can be defined in a "union". In a variable described as the "union" type, any type of data defined by the Union can be loaded. The data is shared with the same memory segment, which has saved space (there is also a space-saving type: Bit domain ). This is a very special feature and also a feature of union. In addition, like struct, Union default access permissions are also public and also have member functions.


2. What is the difference between Union and structure?
"Union" has some similarities with "structure. But they are essentially different. In the structure, each member has its own memory space. The total length of a structure variable is the sum of the member lengths (except for the empty structure, and the boundary adjustment is not considered ). In "Union", each member shares a piece of memory space. The length of a federated variable is equal to the longest length of each member. It should be noted that the so-called sharing here does not mean that multiple members are loaded into a joint variable at the same time, but that the joint variable can be assigned to any member value, however, only one value can be assigned at a time. If a new value is assigned, the old value is washed away.
The following is an example of how to understand deep integration.


Example 4:
# Include <stdio. h>
Void main ()
{
Union number
{/* Define a Union */
Int I;
Struct
{/* Define a structure in the Union */
Char first;
Char second;
} Half;
} Num;
Num. I = 0x4241;/* Union member assignment */
Printf ("% c \ n", num. half. first, num. half. second );
Num. half. first = 'a';/* assign values to structure members in the Union */
Num. half. second = 'B ';
Printf ("% x \ n", num. I );
Getchar ();
}
Output result:
AB
6261

From the above example, we can see that after I is assigned a value, the lower eight bits are the values of first and second. After first and second are assigned a character, the ASCII code of these two characters will also be used as the low-eight-bit and high-eight-bit I.

3. How to define it?


For example:
Union test
{
Test (){}
Int office;
Char teacher [5];
};


Defines a union type named test, which contains two members, one is an integer, the member name is office, the other is a character array, and the array name is teacher. After the joint definition, you can describe the joint variables. variables of the test type can be used to store office integer data or teacher character arrays.


4. How to explain it?
The description of Federated variables can be defined first, then explained, and both described and directly described.


Take the test type as an example:
1) union test
{
Int office;
Char teacher [5];
};
Union test a, B;/* indicates that a and B are of the test Type */
2) union test
{
Int office;
Char teacher [5];
} A, B;
3) union
{
Int office;
Char teacher [5];
} A, B;


Variables a and B are of the test type. The length of variable a and variable B should be equal to the longest length of the member test, that is, the length of the teacher array is equal to 5 bytes in total. For example, if the and B variables are given integer values, only four bytes are used. If the character array is given, five bytes are used.

5. How to use it?
Assign values to the federated variables only to the members of the variables. The member of the federated variable is:
Joint variable name. member name
For example, after a is described as a test variable, you can use a. class, a. office
You are not allowed to assign values only to the federated variable name or perform other operations. You are not allowed to assign values to the federated variables during initialization. Values can only be assigned to programs.
It must be emphasized that only one member value can be assigned to a federated variable at a time. In other words, the value of a federated variable is a member value of the federated variable.


6. Anonymous Union
Anonymous union only notifies the compiler that its member variables share an address. The variables themselves are directly referenced and do not use the common dot operator syntax.

For example:
# I nclude <iostream>
Void main ()
{
Union {
Int test;
Char c;
};
Test = 5;
C = 'a ′;
Std: cout <I <"" <c;
}


As we can see, the Federated component is referenced as a declared common local variable. In fact, for programs, this is exactly how these variables are used. in addition, although defined in a joint declaration, they have the same scope level as any other local variable in the same program. this means that the name of the member in the anonymous union cannot conflict with any other constant identifier in the same scope.
The following restrictions apply to anonymous union:
Because the vertex operator is not used for anonymous union, the elements contained in the anonymous union must be data, and member functions are not allowed or private or protected members are not allowed. In addition, the global anonymous union must be static. Otherwise, it must be placed in an anonymous namespace.


7. Some points to be discussed:
1. What in the Union cannot be stored?
We know that all the items in the Union share the memory, so static and reference cannot be used, because they cannot share the memory.


2. Can classes be combined?


Let's first look at an example:
Class Test
{
Public:
Test (): data (0 ){}
Private:
Int data;
};
Typedef union _ test
{
Test test;
} UI;
But why?
Because consortium cannot store classes with constructors, analysis functions, and copy operators, the compiler cannot guarantee that these objects will not be destroyed because they share the memory, it cannot be guaranteed that the function can be called when it leaves.

3. Why is it anonymous ??


Let's take a look at the next piece of code:
Class test
{
Public:
Test (const char * p );
Test (int in );
Const operator char * () const {return
Data. ch ;}
Operator long () const {return data. l ;}
Private:
Enum type {Int, String };
Union
{
Const char * ch;
Int I;
} Datatype;
Type stype;
Test (test &);
Test & operator = (const test &);
};
Test: test (const char * p): stype
(String), datatype. ch (p ){}
Test: test (int in): stype (Int), datatype. l (I ){
}
Do you see any problems? Haha, compilation and translation fail. Why? Is there a problem with datatype. ch (p) and datatype. l (I?
Haha, where is the problem? Let's take a look at what happened when constructing the test object. when creating the test object, we naturally need to call its corresponding constructor. In the constructor, of course, we need to call the constructor of its members, so he wants to call the constructor of the datatype member, but he does not call the constructor.
Error.


Note that this is not an anonymous union! Because it is followed by a piece of data!


4. How to effectively prevent access errors?


Union can save memory space, but there is also a certain risk: Get the value of the current object through an inappropriate data member! For example, the above ch and I requests are staggered.
To prevent such errors, we must define an additional object to track the value types currently stored in the union. We call this additional object the 'join' discriminant.
A good experience is to provide a set of access functions for all union data types when processing union objects as class members.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.