只使用一个成员的联合的目的是什么? [英] What's the purpose of using a union with only one member?
问题描述
当我阅读 seastar源代码,我注意到有一个名为 tx_side
的联合结构,它只有一个成员。
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?
仅供参考,我将 tx_side
结构粘贴到下面:
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;
推荐答案
因为 tx_side
是一个联合, tx_side()
不会自动初始化/构造 a
和〜tx_side()
不会自动销毁它。
这可以通过 a
和 pending_fifo
的生命周期手动析构函数调用(一个穷人的 std :: optional
)。
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
).
这里有一个例子:
#include <iostream>
struct A
{
A() {std::cout << "A()\n";}
~A() {std::cout << "~A()\n";}
};
union B
{
A a;
B() {}
~B() {}
};
int main()
{
B b;
}
此处, B b;
不打印任何内容,因为 a
既未构造也未破坏。
Here, B b;
prints nothing, because a
is not constructed nor destructed.
如果 B
是结构
, B()
将调用 A()
和〜B()
会调用〜A()
,而您不会能够防止这种情况发生。
If B
was a struct
, B()
would call A()
, and ~B()
would call ~A()
, and you wouldn't be able to prevent that.
这篇关于只使用一个成员的联合的目的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!