Kir*_* KD 1 c++ reference unique-ptr dereference
所以我有一个这样的结构:
struct node {
node_type type;
StaticTokensContainer token_sc;
std::unique_ptr<node> left; // here
std::unique_ptr<node> right; // and here
};
Run Code Online (Sandbox Code Playgroud)
当我尝试编写一个递归函数将 a 转换node为字符串以进行打印时,如下所示:
std::string node_to_string(node n) {
return "<other members converted to strings>" + node_to_string(*(n.left));
}
Run Code Online (Sandbox Code Playgroud)
它给了我:function "node::node(const node &)" (declared implicitly) cannot be referenced -- it is a deleted function
我不明白为什么会出现这个错误,当我(*n)尝试将 n 作为 传递时std::unique_ptr<node>,我没有遇到任何问题,所以我不明白为什么*(n.left)不允许这样做。
您node按值传递,并且不能将一个设置std::unique_ptr为等于另一个:
int main() {
std::unique_ptr<node> a = std::make_unique<node>();
std::unique_ptr<node> b = a; //Error C2280
}
Run Code Online (Sandbox Code Playgroud)
因为现在谁是数据的唯一所有者?
要修复您的错误,只需const在您的函数中引用即可。这样,您就可以传递引用并且不会创建副本:
std::string node_to_string(const node& n) {
return "<other members converted to strings>" + node_to_string(*(n.left));
}
Run Code Online (Sandbox Code Playgroud)
(您还应该考虑退出此函数,否则您将得到堆栈溢出或取消引用的 nullptr,以先到者为准。例如, add if (!n.left) return "";)
| 归档时间: |
|
| 查看次数: |
483 次 |
| 最近记录: |