![](/img/trans.png)
[英]unique_ptr with reinterpret_cast, will the structure get freed correctly?
[英]c++ Using reinterpret_cast to cast unique_ptr<Derived>* to unique_ptr<Base>* for creating a transformable tree structure
我目前正在编写一个需要操作树结构(抽象语法树)的程序。
在树中,一个节点将其子节点作为 unique_ptr 拥有,如下所示:
struct Node {
// to replace node itself in the tree:
// points to unique_ptr that owns this node
// a node can be stored in different unique_ptr types
// -> for example: NodeY could be stored in unique_ptr<NodeY> or unique_ptr<NodeX>)
// -> thus self has to be of type unique_ptr<Node>*
unique_ptr<Node> *self;
// ...
};
struct NodeX: Node {
unique_ptr<Node> child1;
unique_ptr<NodeY> childY;
};
struct NodeY: Node {
unique_ptr<NodeX> child1;
unique_ptr<NodeY> child2;
vector<unique_ptr<NodeY>> otherChildren;
};
struct NodeZ: NodeY {
// ...
};
// and a lot of other nodes with different child types ...
在更改树时,应该可以替换树中的节点。
为此,我在每个节点中存储了一个指向拥有 unique_ptr 的self
指针。 替换操作如下所示:
// could replace node:
void visitNodeY(NodeY *node) {
if (node->someCondition) {
// replace
auto newNode = make_unique<NodeZ>();
unique_ptr<Node> *self = node->self;
// replace with make_unique<NodeA>() would break inheritance hierarchy, but i will not do it :)
*self = move(newNode); // replace and delete old node
node = self.get(); // get new address
node->self = self; // self still points to same address, only contend of unique_ptr has changed
}
}
现在的问题是在构造节点后设置self
指针。
为了实现这一点,我正在使用reinterpret_cast
:
void createNodeX_children(NodeX *nodex) {
// create childY
nodex->childY = make_unique<NodeY>();
// ...
// is that save?
nodex->childY->self = reinterpret_cast<unique_ptr<Node>*>(&nodex->childY);
}
我现在的问题是:是否以这种方式使用 reinterpret_cast 保存,只要我不破坏上面提到的 inheritance 层次结构?
不要reinterpret_cast
。 您可以使用std::unique_ptr
的 构造函数以多态方式转移所有权。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.