C + + Union

Source: Internet
Author: User

What is Union?

It is a common body, or also called a union. When it comes to union, which is the shared body, we have to say a struct, when we have the following definition of a struct:

123456< /td> struct student {      char mark      long num      float score }

The memory structure of the struct will be as shown (demo on x86 machine):
sizeof (struct student) has a value of 12bytes. However, when we define the union as follows,

123456< /td> union test {      char mark      long num      float score }

The value of sizeof (union test) is 4. Why is that? That's what needs to be said. Sometimes we need several different types of variables to exist in the same memory space, as above, we need to store a char type of mark, a long type of num variable, and a float-type score variable in a memory unit that starts at the same address. The three variables above, the char type and the long type occupy a different number of bytes of memory, but in the Union, they are all from the same address, that is, the use of overlay technology, these three variables cover each other, and this makes a number of different variables to share the same memory structure, called "Common body" The structure of the type. The structure of the Union type defined above is as follows:

It also says that the value of sizeof (union test) is 4. Then why is it 4? In general, the memory occupied by the struct struct is the sum of the memory occupied by each member (and of course the memory alignment is also considered). For union, in Rectification's C language programming, the union variable occupies a memory length equal to the length of the longest member's memory. Obviously, this is not true, and the memory-alignment issue needs to be considered for the size of the memory that the Union occupies. This is why sizeof (union test) has a value of 4.

Use Union in C

Say better, and more, after all, is to be used, the following is good to say C in the use of Union. Like a struct, a union must define a common body variable before it can be referenced. And you cannot directly reference a shared body variable, only a member in a pooled variable. Just like the union test I defined above. We cannot directly refer to Union as follows:

12 Union test a; printf("%d", a);

This direct reference is wrong because the store of a has several types, each occupying a different length of storage, and only the shared variable name A is written, so that the compiler cannot determine exactly which member of the output is the value. Therefore, it should be written as follows:

1 printf("%d", a. Mark);

At the same time, when using union, we also need to pay attention to the following points:

  1. The same memory segment can be used to hold several different types of members, but there can only be one at a time, not several at a time. In other words, only one member works at a time, and the other members do not work, that is, they do not both exist and function.
  2. The member that functions in the common body variable is the last member to be deposited, and when a new member is deposited, the original member loses its function. For example, the following code:
    123456789101112131415161718192021222324252627282930 #include <iostream>using namespace std; Union test { Char mark; long num; float score; }a; int main() { //cout<<a<<endl;//Wrong a. Mark = ' b '; cout<<a. Mark<<Endl; //output ' B ' cout<<a. Num<<endl; acsii value of//98 characters ' B ' cout<<a. Score<<Endl; //Output error value a. num = ten; cout<<a. Mark<<Endl; //Output empty cout<<a. Num<<endl; //Output ten cout<<a. Score<<Endl; //Output error value a. Score = 10.0; cout<<a. Mark<<Endl; //Output empty cout<<a. Num<<endl; //Output error value cout<<a. Score<<Endl; //Output ten return 0; }

    So, when using union, be careful with more than.
  3. Because all the member start addresses in the Union are the same, the values for &a.mark, &a.num, and &a.score are the same.
  4. The union variable cannot be used as a function parameter, nor can the function be brought back to the union variable, but a pointer to the union variable is available.
  5. The Union type can appear in a struct type definition, or you can define a union array, whereas a struct can also appear in a union type definition, and an array can also be a member of a union.

Logically, summing up here, the C language of union also has nothing more to say. However, there is a thing called C + +, in this C + + there is a kind of thing called class.

When union encounters an object

In the case of the Union in C alone, the sum above is sufficient, but now there is a thing called C + +; When Union encounters objects in C + +, everything gets cut and messed up. The Union usage rule summarized above is still applicable in C + +. The union was originally from the C language, and if we continue to use Union in C + + in the same way as it does, there is no problem. What if we put a class object in the Union? What would be the result? For example, the following code is available:

123456789101112131415161718 #include <iostream>using namespace std; class CA { int m_a; };Union Test { CA a; double d; }; int main() { return 0; }

As you can see, there is no problem; if we add a constructor to a class CA, or add a destructor, we will find that the program will have an error. You cannot define static, reference-type variables because the contents of the Union share memory. Because it is not allowed in the Union to store objects with classes such as constructors, destructors, and copy constructors, the corresponding class object pointers can be stored. The compiler cannot guarantee that the constructors and destructors for the class are properly called, so a memory leak can occur. So, when we use Union in C + +, try to keep the union style in C and try not to have the union with the object.

C + + Union

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.