当我阅读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;
Run Code Online (Sandbox Code Playgroud)
Hol*_*Cat 61
因为tx_side
是联合,tx_side()
所以不会自动初始化/构造a
,~tx_side()
也不会自动对其进行破坏。这样可以通过放置新的和手动的析构函数调用(可怜的人)对a
和的生命周期进行细粒度的控制。pending_fifo
std::optional
这是一个例子:
#include <iostream>
struct A
{
A() {std::cout << "A()\n";}
~A() {std::cout << "~A()\n";}
};
union B
{
A a;
B() {}
~B() {}
};
int main()
{
B b;
}
Run Code Online (Sandbox Code Playgroud)
在此,不B b;
打印任何内容,因为a
既不构造也不破坏。
如果B
是struct
,B()
将调用A()
,然后~B()
调用~A()
,那么您将无法避免这种情况。