【发布时间】:2020-07-01 23:17:21
【问题描述】:
我想使用 RTTI 克隆一个唯一指针向量。
目前,有一个抽象基类Node 和派生类Element 和TextNode。 Element 包含唯一的 Node 指针向量。
我能够创建Element 类型的对象并将其移动到向量中。我希望能够克隆 Element 并将副本推送到向量中,但我正在努力使用 Element 的复制构造函数。
这可能吗?如何使用 RTTI 克隆唯一指针?有没有更好的方法来解决这个问题?
#include <iostream>
#include <memory>
#include <string>
#include <vector>
struct Node {
virtual ~Node() = default;
virtual std::string toString() const = 0;
};
struct Element : Node {
Element() = default;
Element(const Element &element) {
// clone children
// for (const auto &child : element.children) children.push_back(std::make_unique</* get RTTI */>(child));
}
Element(Element &&) = default;
std::string toString() const override {
std::string str = "<Node>";
for (const auto &child : children) str += child->toString();
str += "</Node>";
return str;
}
std::vector<std::unique_ptr<Node>> children;
};
struct TextNode : Node {
std::string toString() const override { return "TextNode"; }
};
int main() {
Element root;
Element node;
node.children.push_back(std::make_unique<TextNode>());
// This copy doesn't work because I don't know how to implement the copy constructor
root.children.push_back(std::make_unique<Element>(node));
root.children.push_back(std::make_unique<Element>(std::move(node)));
root.children.push_back(std::make_unique<TextNode>());
std::cout << root.toString();
}
实际输出:
TextNode TextNode
预期输出:
TextNode TextNode TextNode
【问题讨论】:
标签: c++ unique-ptr