到目前为止,我只使用联合体来存储成员A或成员B。
现在我发现自己需要在运行时更改所使用的成员。
union NextGen {
std::shared_ptr<TreeRecord> Child = nullptr;
std::vector<std::shared_ptr<TreeRecord>> Children;
};
我的当前使用情况:
void TreeRecord::AddChild(const std::shared_ptr<TreeRecord>& NewChild) {
if(_childCount == 0) {
_nextGeneration.Child = NewChild;
_childCount++;
} else if(_childCount == 1) {
//This is not clear to me:
//Do I have to set Child to nullptr first?
//Do I need to clear the Children vecor?
//Or will it work like this?
_nextGeneration.Children.push_back(_nextGeneration.Child);
_nextGeneration.Children.push_back(NewChild);
_childCount++;
} else {
_nextGeneration.Children.push_back(NewChild);
_childCount++;
}
}
新实现(尝试):
typedef std::shared_ptr<TreeRecord> singlechild_type;
typedef std::vector<std::shared_ptr<TreeRecord>> children_type;
union {
singlechild_type _child;
children_type _children;
};
void TreeRecord::AddChild(const singlechild_type& NewChild) {
if(_childCount == 0) {
_child = NewChild;
_childCount = 1;
} else if(_childCount == 1) {
singlechild_type currentChild = _child; //Copy pointer
_child.~singlechild_type(); //Destruct old union member
new (&_children) children_type(); //Construct new union member
_children.push_back(currentChild); //Add old child to vector
_children.push_back(NewChild); //Add new child to vector
_childCount = 2;
} else {
_children.push_back(NewChild);
_childCount++;
}
}