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;
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With