我试图实现一个标记联合。
我的理解是,在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"
同样具有可移植性,并且不会尝试在每行刷新输出。 - HTNWstd::variant
的实现。 - M.M