我提出的问题不是作业问题,但我正在考虑在作业中使用这些概念。如果它有帮助,上下文是这样的:我需要跟踪几个union实例,它们属于我自己的一个类中作为类变量的联合。 (注意:union实例的数量是未知的,所以我不能只有一个固定数量的union实例。
Q1:如果我有工会,请说MyUnion, 和这个联盟的许多例子, 我可以将它们放入矢量中 像
vector<union MyUnion> myVector(10);
Q2:指针是否有效 联盟?像
union MyUnion *myUnionPtr = new union myUnion;
问题3:我正在考虑使用矢量 在我的联盟指针 实施,就是这个概念 正确?这也是正常的 在C ++中的方法?我需要吗? 重新考虑我的设计?
答案 0 :(得分:12)
MyUnion* ptr = new MyUnion();
默认情况下,所有类型都是CopyConstructable和Assignable。 (“可复制”用于表示这些概念的并集,但是标准单独指定它们。)这是因为复制ctors和op =被添加到类(联合是一个类类型),除非在某些情况下。有一些references在线,但我不知道有一个,可以在网上免费获得,拼出这些。
你必须不遗余力地阻止它,例如:
示例:
union CopyableUnion {
int n;
char c;
double d;
};
union NonCopyableUnion {
int n;
char c;
double d;
NonCopyableUnion() {} // required, because any user-defined ctor,
// such as the private copy ctor below, prevents the supplied
// default ctor
private:
NonCopyableUnion(NonCopyableUnion const&);
NonCopyableUnion& operator=(NonCopyableUnion const&);
};
int main() {
CopyableUnion a;
CopyableUnion b = a; // fine, uses copy ctor
b = a; // fine, uses op=
NonCopyableUnion c;
NonCopyableUnion d = c; // compile error (copy ctor)
d = c; // compile error (op=)
return 0;
}
注意:只是因为某些东西是可复制的,并不意味着它可以做你想要的!例如:
struct A {
int* p;
A() : p(new int()) {}
// the provided copy ctor does this:
//A(A const& other) : p(other.p) {}
// which is known as "member-wise" copying
~A() { delete p; }
};
int main() {
A a;
{
A b = a;
assert(b.p == a.p); // this is a problem!
} // because when 'b' is destroyed, it deletes the same pointer
// as 'a' holds
return 0; // and now you have Undefined Behavior when
// ~A tries to delete it again
}
当然,同样的事情也适用于工会。不过,该修正同样适用:
struct A {
int* p;
A() : p(new int()) {}
A(A const& other) : p(new int(*other.p)) {}
~A() { delete p; }
};
(如果你发现它,是的,如果你试图使用op =,A就会出现问题,就像它最初使用复制ctor一样。)