[英]Binary Tree with std::unique_ptr
I'm actually using std::unique_ptr
in order to create a binary tree. 我实际上是使用
std::unique_ptr
来创建一个二叉树。
In fact, I use an algorithm tour, which from a distance matrix, calculates the shortest path ! 实际上,我使用算法巡视,它根据距离矩阵来计算最短路径! In my algorithm, I found myself confronted with the problem of
std::move()
with std::unique_ptr
. 在我的算法中,我发现自己遇到了
std::unique_ptr
的std::move()
问题。
My tree is built, but only on the root node and don't "make branch". 我的树是构建的,但仅在根节点上构建,而不是“ make branch”。
Here the code where I have the problem : 这是我遇到问题的代码:
node = std::move(node.get()->addChild());
The function addChild
returns a reference of the new child (= std::unique_ptr<Node>)
. 函数
addChild
返回new child (= std::unique_ptr<Node>)
的引用。
I really need to "change" node in order to complete my algorithm. 我确实需要“更改”节点才能完成我的算法。 So, How can I fix it ?
那么,我该如何解决呢?
Change addChild
to return the new node's unique_ptr
by value instead of returning a reference. 更改
addChild
以按值返回新节点的unique_ptr
而不是返回引用。 The result will be an rvalue without requiring a cast with std::move
. 结果将是右值,而无需强制转换为
std::move
。 In your current code, you pass an lvalue reference to std::move
which results in it still being an lvalue reference and attempting to invoke the copy constructor instead of move constructor of std::unique_ptr
. 在当前代码中,您将一个左值引用传递给
std::move
,这导致它仍然是一个左值引用,并尝试调用副本构造函数而不是std::unique_ptr
的move构造函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.