【发布时间】:2020-06-24 12:45:58
【问题描述】:
我正在尝试实现标记联合。
我的理解是,在 C++ 联合中,非静态成员的非平凡(即非空)析构函数从不调用,因此我们必须自己调用它们。我就是这样做的:
#include <iostream>
class C {
public:
C() {
std::cout << "C Ctor" << std::endl;
}
~C() {
std::cout << "C Dtor" << std::endl;
}
};
class B {
public:
B() {
std::cout << "B Ctor" << std::endl;
}
~B() {
std::cout << "B Dtor" << std::endl;
}
};
struct S {
int type;
union U {
C c;
B b;
U() {
}
~U() {}
} u;
S(int type) : type(type) {
if (type == 0) {
u.c = C();
} else {
u.b = B();
}
}
~S() {
if (type == 0) {
u.c.~C();
} else {
u.b.~B();
}
}
};
int main() {
S s(0);
return 0;
}
但是,输出是:
C Ctor
C Dtor
C Dtor
意思是,C 析构函数被调用了两次,而不是一次。
发生了什么事?如果您发现我的标记联合实施存在其他问题,请指出。
【问题讨论】:
-
仅供参考:
std::endl通常是不必要的。"\n"具有同样的便携性,不会尝试在每一行刷新输出。 -
通常你会使用一个匿名联合来实现一个标记联合,你可以在标准中阅读这些内容和/或查看
std::variant的实现。跨度>
标签: c++ union destructor