【问题标题】:c++ Using reinterpret_cast to cast unique_ptr<Derived>* to unique_ptr<Base>* for creating a transformable tree structurec++ 使用 reinterpret_cast 将 unique_ptr<Derived>* 转换为 unique_ptr<Base>* 以创建可转换的树结构
【发布时间】:2020-07-17 07:59:59
【问题描述】:

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

在更改树时,应该可以替换树中的节点。
为此,我在每个节点中存储了一个 self 指向拥有 unique_ptr 的指针。 替换操作如下所示:

// 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 保存?

【问题讨论】:

  • reinterpret_cast 并不是真正在任意类型之间进行转换。有一个您可以使用它的允许转换列表 (en.cppreference.com/w/cpp/language/reinterpret_cast)。如果您不在列出的任何一种情况下,则说明您使用了 reinterpret cast wrong

标签: c++ tree abstract-syntax-tree unique-ptr reinterpret-cast


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2018-12-15
    • 2014-03-27
    • 2019-05-24
    • 2020-01-30
    • 2016-07-23
    • 2015-08-08
    • 1970-01-01
    • 1970-01-01
    • 2021-10-09
    相关资源
    最近更新 更多