What's the purpose of using a union with only one member?

前端 未结 2 743
独厮守ぢ
独厮守ぢ 2021-01-30 06:17

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

相关标签:
2条回答
  • 2021-01-30 06:40

    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.

    0 讨论(0)
  • 2021-01-30 06:47

    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.

    0 讨论(0)
提交回复
热议问题