使用一个只有一个成员的工会的目的是什么?

当我阅读 Seastar 源代码时,我注意到有一个名为 tx_side的联合结构,它只有一个成员。这是用来解决某个问题的黑客技术吗?

仅供参考,我粘贴了下面的 tx_side结构:

union tx_side {
tx_side() {}
~tx_side() {}
void init() { new (&a) aa; }
struct aa {
std::deque<work_item*> pending_fifo;
} a;
} _tx;
5710 次浏览

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.

In simple words, unless explicitly assigned/initialized a value the single member union does not initialize the allocated memory. This functionality can be achieved with std:: optional in c++17.