只使用一个成员的联合的目的是什么? [英] What's the purpose of using a union with only one member?

查看:58
本文介绍了只使用一个成员的联合的目的是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我阅读 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()不会自动销毁它。
这可以通过 new和精确控制 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屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆