c ++使用reinterpret_cast来将unique_ptr *转换为unique_ptr *以创建可变形树结构

问题描述 投票:-1回答:1

我目前正在编写一个需要操纵树结构(抽象语法树)的程序。在树中,节点将其子节点作为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保存?

c++ tree abstract-syntax-tree unique-ptr reinterpret-cast
1个回答
1
投票

不要reinterpret_cast。您可以使用std::unique_ptrconstructors多态转让所有权。

© www.soinside.com 2019 - 2024. All rights reserved.