Introduction to union in C++

union introduction

  A union, also called a union, can define a variety of different data types in a "union", and a variable that is described as the type of the "union" is allowed to load any data defined by the "union" , these data share the same memory to achieve the purpose of saving space. The memory length occupied by the union variable is equal to the memory length of the longest member.

Union and struct comparison

Let's look at an example about struct:

struct student
{
     char mark;
     long num;
     float score;
};

The memory structure of its struct is as follows, and the value of sizeof(struct student) is 12bytes.

The following are examples of unions:

union test
{
     char mark;
     long num;
     float score;
};

The value of sizeof(union test) is 4. Because the union stores a mark of char type, a num variable of long type and a score variable of float type in the memory unit starting from the same address , and the number of memory bytes occupied by char type and long type is different Yes, but they are all stored from the same address in the union, that is, the overlay technology used, these three variables overwrite each other, and this structure that makes several different variables occupy the same memory is called "shared Body" type of structure. The structure of its union type is as follows:

Since the starting addresses of all members in the union are the same, the values ​​of &a.mark, &a.num, and &a.score are all the same.

cannot be used as follows:

union test a; 
printf("%d", a); //error

Since there are several types of storage areas of a, which occupy storage areas of different lengths, only the name of the union variable a is written, so that the compiler cannot determine the value of which member to output.

printf("%d", a.mark); //Correct

test endianness

One usage of union is to test whether the CPU is in big-endian mode or little-endian mode:

#include <iostream>
using namespace std;

void checkCPU()
{
    union MyUnion{
        int a;
        char c;
    }test;
    test.a = 1;
    if (test.c == 1)
        cout << "little endian" <<endl;
    else cout << "big endian" <<endl;
}

int main()
{
    checkCPU();
    return 0;
}

For example, the code is as follows:

#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; // ASCII value of 98 character 'b' 
     cout<<a.score<<endl; // output error Value 

     a.num = 10; 
     cout<<a.mark<<endl; // output line break, thank you suxin for your correction 
     cout<<a.num<<endl; // output 10 
     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 10

     return 0;
}

Union in C++

The union usage rules summarized above still apply in C++. What if the object is added?

#include <iostream>
using namespace std;

class CA
{
     int m_a;
};

union Test
{
     CA a;
     double d;
};

int main()
{
     return 0;
}

The above code runs without problems.

If you add a constructor or a destructor  to the class CA , you will find that the program will go wrong. Since the things in the union share memory, static and reference-type variables cannot be defined. Because objects of classes with constructors, destructors, and copy constructors are not allowed to be stored in union, but corresponding class object pointers can be stored. The compiler cannot guarantee that the constructor and destructor of the class are called correctly, so memory leaks may occur. Therefore, when using union in C++, try to keep the style of using union in C language, and try not to let union have objects.

Guess you like

Origin blog.csdn.net/std7879/article/details/125001689