Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the purpose of using a union with only one member?

Tags:

c++

unions

c++14

When I was reading seastar source code, I noticed that there is a union structure called tx_side which has only one member. Is this some hack to deal with a certain problem?

FYI, I paste the tx_side structure below:

union tx_side {     tx_side() {}     ~tx_side() {}     void init() { new (&a) aa; }     struct aa {         std::deque<work_item*> pending_fifo;     } a; } _tx; 
like image 691
daoliker Avatar asked Nov 27 '19 09:11

daoliker


People also ask

Can a union have member functions?

A union can have member functions (including constructors and destructors), but not virtual functions. A union cannot have base classes and cannot be used as a base class. A union cannot have non-static data members of reference types.

What is the purpose of union in C?

A union is a special data type available in C that allows to store different data types in the same memory location. You can define a union with many members, but only one member can contain a value at any given time. Unions provide an efficient way of using the same memory location for multiple-purpose.

What are the advantages of union in C?

Advantages of unionIt occupies less memory compared to structure. When you use union, only the last variable can be directly accessed. Union is used when you have to use the same memory location for two or more data members. It enables you to hold data of only one data member.


1 Answers

Because tx_side is a union, tx_side() doesn't automatically initialize/construct a, and ~tx_side() doesn't automatically destruct it. This allows a fine-grained control over the lifetime of a and pending_fifo, via placement-new and manual destructor calls (a poor man's std::optional).

Here's an example:

#include <iostream>  struct A {     A() {std::cout << "A()\n";}     ~A() {std::cout << "~A()\n";} };  union B {     A a;     B() {}     ~B() {} };  int main() {     B b; } 

Here, B b; prints nothing, because a is not constructed nor destructed.

If B was a struct, B() would call A(), and ~B() would call ~A(), and you wouldn't be able to prevent that.

like image 195
HolyBlackCat Avatar answered Oct 12 '22 01:10

HolyBlackCat