簡體   English   中英

c++ 使用 reinterpret_cast 投射 unique_ptr<derived> * 到 unique_ptr<base> * 用於創建可轉換的樹結構</derived>

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM