For the union I used less, most of the recent time using LUA, so review the Union
Union is a common body, as the name implies, a common piece of memory
A piece of memory different access mode
//1. Easy access to arrays//two equivalent access modes for a piece of memoryTemplate <typename t>Union mat4x4 {struct{T m00, M01, M10, M11; }; T m[2][2];};intMainintargcConst Char*argv[]) {mat4x4<float> Mat = {1,2,3,4}; Std::cout<< mat.m00 <<Std::endl; Std::cout<< mat.m[0][0] <<Std::endl; //output:1//1 return 0;}Splitting a variable into bytes access
intMainintargcConst Char*argv[]) {Union INT4 {struct{unsignedChar_1, _2, _3, _4; }; int_int; }; Int4 integer; Integer._int=100000000; printf ("%08x\n", Integer._int); printf ("%02x\n", integer._1); printf ("%02x\n", integer._2); printf ("%02x\n", Integer._3); printf ("%02x\n", Integer._4); //Output://05f5e100//xx//E1//F5// to return 0;}Determine the CPU size end problem
intBig_endian (void) {union{Longl; Charc[sizeof(Long)]; }u; U.L=1; return(u.c[sizeof(Long) -1] ==1);}intMainintargcConst Char*argv[]) { //In the big- endian format, the high byte of the character data is stored in the low address, while the low byte of the word data is placed in the high address//In contrast to the big-endian storage format, in the small-end storage format, the low address is stored in the low byte of the word data, high address is stored in the high byte of the word data if(!Big_endian ()) {printf ("CPU is small-end mode \ n"); } Else{printf ("CPU is in big-endian mode \ n"); }}The memory footprint of the Union
The first memory footprint must be greater than the largest one, followed by memory alignment
intMainintargcConst Char*argv[]) { //# Memory IssuesUnion Max {Char_1; int_4; Double_8; Char_17[ -]; }; printf ("Size:%lu\n",sizeof(Max)); //output:size:24 return 0;}
Union is a C-language thing, and of course there is in C + +, but there are some areas in C + + that union has to pay attention to.
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 Language Union