繁体   English   中英

c ++ 14 unique_ptr并使用删除的函数'std :: unique-ptr'使用unique_ptr错误

[英]c++14 unique_ptr and make unique_ptr error use of deleted function 'std::unique-ptr'

我有这样的功能..

unique_ptr<Node> test(unique_ptr<Node> &&node, string key)
{
    if(!node)
    {
        return make_unique<Node>(key);
    }
    else
        return node;
}

如果节点为null,我想创建一个节点,或者返回节点。 但它错误地说“使用已删除的函数'std :: unique_ptr'”。 我做错了什么?

问题是你调用函数的方式。 但首先你应该接受你的std::unique_ptr值,而不是r-reference

然后在调用函数时需要std::move()指针:

// accept by value
std::unique_ptr<Node> test(std::unique_ptr<Node> node)
{
    if(!node)
        return std::make_unique<Node>();

    return node;
}

int main()
{
    auto n = std::make_unique<Node>();

    n = test(std::move(n)); // move the pointer
}

无法复制std::unique_ptr否则它将不是唯一的。 你要移动他们。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM