且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

试图引用已删除函数的结构匿名未标记联合错误

更新时间:2021-08-24 03:15:16

您的代码在这里和那里缺少一些分号,并且联合缺少成员名称.我已经做了一些更改,希望代码仍能反映您的情况.是的,有关于联合的标准更改:在 C++11 之前,不允许具有非平凡构造函数的联合成员.从 11 开始它们是,但是联合还必须提供一个构造函数.所以,我猜你的代码确实是在 vs2008 下编译的,原因是 MS 的非标准语言扩展.

Your code was missing some semicolons here and there, and the union was missing member names. I've made a few changes of which I hope that the code still reflects your case. Yes, there were standard changes with respect to unions: before C++11, union member with non-trivial constructors were not allowed. From 11 onwards they are, but then the union must also provide a constructor. So, I guess that your code did compile under vs2008 due to a non-standard language extension of MS.

为了让您的代码运行,您需要的是一个析构函数,它调用构造的联合成员的适当析构函数.那么你必须知道,构建了哪个成员.我在下面通过添加 enum class which_tm_which 成员解决了这个问题.

What you need, to get your code going, is a destructor which calls the appropriate destructor of the constructed union member. Then you must know, which member was constructed. I've solved that below by adding an m_which member of enum class which_t.

另一个解决方案是去掉析构函数~A()~B().

Another solution is getting rid of the destructors ~A() and ~B().

您也可以考虑使用 std::variant,它在 C++17 以后的标准库中.它可以替代联合和类似联合的类的许多用途.

You may also consider using std::variant, which is in the standard library from C++17 onwards. It can replace many uses of unions and union-like classes.

using WORD = unsigned short;

//////////////////////////////////////////////////////////////////////

struct A
{
    WORD insideA;
    explicit A(WORD x) : insideA(x)
    {}
    ~A() {}
};

struct B
{
    WORD insideB;
    explicit B(WORD x) :insideB(x)
    {}
    ~B() {}
};

enum class which_t
{
    dataA,
    dataB,
    wX
};

struct AB
{
    union
    {
        A dataA;
        B dataB;
        WORD wX;
    };
    which_t m_which;
    AB(A const& a) // maybe you wanna leave out 'explicit' here
        : dataA(a)
        , m_which(which_t::dataA)
    {}
    AB(B const& b) // maybe you wanna leave out 'explicit' here
        : dataB(b)
        , m_which(which_t::dataB)
    {}
    AB(WORD x) // maybe you wanna leave out 'explicit' here
        : wX(x)
        , m_which(which_t::wX)
    {}
    ~AB()
    {
        switch (m_which)
        {
        case which_t::dataA:
            dataA.~dataA();
            break;
        case which_t::dataB:
            dataB.~dataB();
            break;
        case which_t::wX:
            break;
        }
    }
};

struct USAGE
{
    AB usageAB;
    explicit USAGE(AB& parAB)
        : usageAB(parAB) //<< attempting to reference a deleted function
    {}
};

//////////////////////////////////////////////////////////////////////

int main()
{
    AB ab1(A{ 1 });
    USAGE usage1(ab1);
    AB ab2(B{ 2 });
    USAGE usage2(ab2);
    AB ab3(3);
    USAGE usage3(ab3);
}