最近,我尝试将我的 VS2008 c++ 项目转换为 VS2019,因为需要更新库、支持等,我有片段,在 VS2008 上编译,但不是在 vs2019 上
struct A
{
WORD insideA;
A(): insideA(0)
{}
~A(){}
}
struct B
{
WORD insideB;
B():insideB(0)
{}
~B(){}
}
struct AB
{
union
{
struct { A dataA; };
struct
{
WORD wX;
B dataB;
}
}
AB()
:wX(0)
{}
}
struct USAGE
{
AB usageAB;
USAGE(AB &parAB)
: usageAB(parAB) //<< attempting to reference a deleted function
{}
}
vs2008 和 vs2019 之间匿名联合的标准有什么变化吗?
您的代码到处缺少一些分号,并且工会缺少成员名称。我做了一些更改,我希望代码仍然反映您的情况。是的,关于联合有标准的更改:在 C++11 之前,不允许具有非平凡构造函数的联合成员。从 11 开始就是这样,但是 union 还必须提供一个构造函数。所以,我猜你的代码确实在 vs2008 下编译,因为 MS 的非标准语言扩展。
为了让代码运行,您需要一个析构函数,它调用构造的联合成员的适当析构函数。那么你必须知道,是哪个成员被构建的。我通过添加
m_which
的 enum class which_t
成员解决了下面的问题。
另一个解决方案是摆脱析构函数
~A()
和 ~B()
。
您还可以考虑使用
std::variant
,它是从C++17开始的标准库中的。它可以取代联合体和类似联合体的类的许多用途。
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);
}