- 如果工會是CopyConstructable和分配的,那麼它滿足的std ::載體的要求。
- 是:
MyUnion* ptr = new MyUnion();
- 指針的容器在某些情況下工作,但如果你想擁有指針的容器,看Boost的ptr_* containers。然而,在這裏看起來你要麼有一個非指針的容器,要麼是一個非擁有指針的容器,其中任何一個對於向量來說都是很好的和通用的。
所有類型,默認情況下,無論是CopyConstructable和轉讓。 (「可複製」用於表示這些概念的聯合,然而標準單獨指定它們。)這是因爲複製ctors和op =被添加到類(聯合是一個類類型),除非在某些情況下。有幾個references在線,但我不知道有一個可以在線免費下載的拼寫單元,可以將它們拼出來。
你必須走出自己的方式來防止它,如:
- 使拷貝構造函數或OP =非公開
- 使拷貝構造函數或OP =採取非const參考
- 得到類型的非CopyConstructable或非可分配構件
實施例:
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 =,在用同樣的方法,因爲它原本與副本ctor。)
如何確定聯合是否爲CopyConstructable和Assignable? – derrdji 2009-11-23 21:45:07
@derrdji:我認爲只要所有成員都(不明確否認),而且工會本身並沒有明確否認。 – Sydius 2009-11-23 23:13:54