Union in C ++

Source: Internet
Author: User

We should use Union according to convention in C. This is my article.ArticlePoints to be given. Although C ++ allows us to expand some new things, I suggest you do not do that. After reading this article, I think you probably think so too.
C. Because there is no concept of class, all types can be considered as a combination of basic types, it is natural to include struct in union, after C ++, since it is generally believed that struct in C ++ is basically equivalent to class, can there be class members in union? Let's take a look at the followingCode:

Struct testunion
{
Testunion (){}
};

Typedef Union
{
Testunion OBJ;
} Ut;

Int main (void)
{
Return 0;
}
CompileProgram, We will be notified:
Error c2620: Union '_ unnamed': Member 'obj 'has user-defined constructor or non-trivial default constructor
If the constructor with nothing to do is removed, everything is OK.

Why does the compiler not allow our union members to have Constructors? I cannot find an authoritative explanation of this issue. For this question, my explanation is:

If the C ++ standard allows our Union to have constructors, do we need to execute this constructor during space allocation? If the answer is yes, if the testunion constructor contains some memory allocation operations or other modifications to the entire application state, if I want to use OBJ in the future, it may be reasonable, but what if I don't use the OBJ member at all? The modification to the system status caused by the introduction of obj is obviously unreasonable; otherwise, if the answer is no, once we select OBJ for future operations, all information is not initialized (if it is a normal struct, there is no problem, but what if there is a virtual function ?). Furthermore, let's assume that our Union is not only one testunion OBJ, but also one testunion2 obj2. Both of them have constructors, in addition, some memory allocation tasks are executed in the constructor (many other tasks are done). If obj is constructed first, and obj2 is constructed later, then the execution result will almost certainly cause memory leakage.

In view of the above troubles (there may be more trouble), when constructing a union, the compiler is only responsible for allocating space and not executing additional initialization tasks. In order to simplify the work, as long as the constructor is provided, the above error will be received.

Likewise, except constructors, destructor, copy constructors, and value assignment operators cannot be added.

In addition, if our class contains any virtual functions, we will receive the following error message during compilation:
Error c2621: Union '_ unnamed': Member 'obj 'has copy constructor

Therefore, the idea that Union contains class member variables with Constructors/destructor/copy constructors/assign value operators/virtual functions is dispelled, be honest with your C-style struct!
However, defining a common member function is OK, because it does not make any essential difference between the class and the C-style struct, you can fully understand this class as a C-style struct + N global functions.

Now let's look at the differences when the class contains internal union. Take a look at the following procedures and read the program prompts:

Class testunion
{
Union dataunion
{
Dataunion (const char *);
Dataunion (long );
Const char * CH _;
Long L _;
} Data _;

Public:
Testunion (const char * Ch );
Testunion (long L );
};

Testunion: testunion (const char * Ch): Data _ (CH) // if you want to use initialing list to initiate a nested-union member, the Union must not be anonymous and must have a constructor.
{}

Testunion: testunion (long l): Data _ (l)
{}

Testunion: dataunion (const char * Ch): CH _ (CH)
{}

Testunion: dataunion (long l): L _ (l)
{}

Int main (void)
{
Return 0;
}

As shown in the above program, union in C ++ can also contain constructors. However, although this is supported by languages, it is really a bad programming habit. Therefore, I don't want to explain too much about the above program. I recommend the following programming style:

Class testunion
{
Union dataunion
{
Const char * CH _;
Long L _;
} Data _;

Public:
Testunion (const char * Ch );
Testunion (long L );
};

Testunion: testunion (const char * Ch)
{
Data _. CH _ = CH;
}

Testunion: testunion (long l)
{
Data _. L _ = L;
}

Int main (void)
{
Return 0;
}

It is completely C-style.

So accept this conclusion:
Use Union according to convention in C. Try not to use any additional C ++ features.

Union is a good thing, and union is a struct. All members in the Union share a piece of memory, which is determined by the size of the largest member. when accessing members, the memory is parsed as a member; in gamedev, Union can make a difference in these aspects:
1. Name Change:
Struct rename
{
Public:
Union
{
Struct
{
Float X, Y, Z, W;
};
Struct
{
Float VEC [4];
};
};
};
In this way, we can access the variable according to the specific meaning, or the loop like an array;

2. Compression:
Struct Compression
{
Public:
Bool operator = (const compression & Arg) const {return value = Arg. value ;}
Union
{
Struct
{
Char A, B, C, D, E, F, G;
};
Struct
{
Long long value;
};
};
};
In this way, for centralized processing, such as =, the efficiency will be greatly improved. For example, on a 64-bit machine, it is very convenient to compress and decompress data once or when data is transmitted;
3. Danger:
The anonymous Union usage is not standard, so you must confirm on compiler ==> the portability of the compiler is not good;
The size of data on different machine operating systems is different, indicating different, so it is dangerous to use Union, especially during transplantation;
However, if the system and compiler are both the same, it is okay to use union in a proper place.

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.