首先,如果mValue
是一个指向动态分配内存的指针,那么这个类的默认拷贝构造函数是非常不安全的,除非你很乐意泄漏内存。
因为,哪个副本负责删除对象?它们看起来完全相同,并且没有共享指针。所以我认为你只是泄露了它。 (也许你有一些“经理”班?但是那么你不会问如何在工会现在存储它的价值,你会吗?因此,tsk tsk泄漏:p)
在大多数情况下,你想要存储一个额外的标志,告诉你哪个成员正在被初始化。然后它被称为“歧视联盟”,因为有实际的信息可以用来区分它所处的两种状态中的哪一种。
我会给出一个最小版本,假设ValueT
是可复制和移动的。
template<typename ValueT, typename ChildT>
class MyUnion
{
public:
// Accessors, with ref qualifiers.
bool have_value() const { return mHaveValue; }
ValueT & get_value() & { return mValue; }
ValueT && get_value() && { return std::move(mValue); }
ValueT const & get_value() const & { return mValue; }
ChildT * & get_child() & { return mChild; }
ChildT * && get_child() && { return mChild; }
ChildT * const & get_child() const & { return mChild; }
// Constructors. Default, copy, and move.
MyUnion() {
this->init_child(nullptr);
}
MyUnion(const MyUnion & other) {
if (other.have_value()) {
this->init_value(other.get_value());
} else {
this->init_child(other.get_child());
}
}
MyUnion(MyUnion && other) {
if (other.have_value()) {
this->init_value(std::move(other.get_value()));
} else {
this->init_child(std::move(other.get_child()));
}
}
// Move assignment operator is easier, do that first.
// Note that if move ctors can throw, you can get a UB with this.
// So in most correct code, you would either ban such objects from
// appearing in your union, or try to make backup copies in order
// to recover from the exceptions. In this code, I will just
// assume that moving your object doesn't throw.
// In that case, it's just deinitialize self, then use code from
// move ctor.
MyUnion & operator = (MyUnion && other) {
this->deinitialize();
if (other.have_value()) {
this->init_value(std::move(other.get_value()));
} else {
this->init_child(std::move(other.get_child()));
}
return *this;
}
// Copy ctor basically uses "copy and swap", but instead of
// swap, we use move assignment. This is exception safe, if
// move assignment is.
MyUnion & operator = (const MyUnion & other) {
MyUnion temp{other};
*this = std::move(temp);
return *this;
}
// Dtor simply calls deinitialize.
~MyUnion() { this->deinitialize(); }
private:
union {
ChildT* mChild;
ValueT mValue;
};
bool mHaveValue;
// these next three methods are private helpers for you.
// the users of your class should not mess with these things,
// or UB is quite likely!
void deinitialize() {
if (mHaveValue) {
mValue.~ValueT();
} else {
// pointer type has no dtor. But if you actually *own* the child,
// then you should call delete here I guess.
// Or, replace with `std::unique_ptr` and call
// that guys dtor. RAII is your friend, you can thank me later.
}
}
// Initialize the value, using perfect forwarding.
// Only do this if mValue is not currently initialized!
template <typename ... Args>
void init_value(Args && ... args) {
new (&mValue) ValueT(std::forward<Args>(args)...);
mHaveValue = true;
}
// Here, mChild is a raw pointer, so it doesn't make sense to
// make a similar initialization. But if you change it to be an RAII
// object, then you should probably do a similar pattern to above,
// with perfect forwarding.
void init_child(ChildT * c) {
mChild = c;
mHaveValue = false;
}
};
注意:您通常不需要像这样滚动您自己的区分联合。很多时候,最好使用一些现有库,如boost::variant
或评论中提到的expected
类型之一。但是,让自己的小判别联合这样是
- 并不难
- 一个很好的锻炼
- ,则有时需要出现在API边界或东西
一个好主意在很多情况下,使用联合是一种不必要的优化,只需一个struct
即可。它需要更多的记忆才能表达对象,但这很少重要,并且可能会让团队更容易理解/更容易维护。
不,一般来说,你可能不会使用memcpy。正是这样一种类似'std :: string'的类“非平凡”(不是简单地可复制的,确切地说)。您需要一些方法来了解哪些联合成员当前处于活动状态,并相应地编写您的复制构造函数。或者,使用['boost :: variant'](http://www.boost.org/doc/libs/1_61_0/doc/html/variant.html) –
'ValueT'也需要复制&移动构造函数/赋值/等等。它会使这个任务变得简单很多,因为只要MyUnion是可以复制构建和移动构造的。即使POD可以使用初始化副本和“std :: move”afaik –
@XerenNarcy问题不在于如何复制成员,就像知道要复制哪个成员一样。 –